Monday, 15 August 2011

javascript - How to keep the selection in a div when I focus in another element in the page? -



javascript - How to keep the selection in a div when I focus in another element in the page? -

i'm working in text editor , have made great benefit of @timdown 's rangy lib, when select text , focus in text input write link on it, this link applied selection later, lose selection , selection becomes unselected!

you can save selection in variable folowing:

var sel = window.getselection().getrangeat(0); //get cursor position sel = [[sel.startcontainer,sel.startoffset], [sel.endcontainer,sel.endoffset] ]; //save cursor position (start , end); /*do whatever, allow user alter selected element*/

now when have selection in variable, can whatever want. nodes involved in selection must not changed, or selection point on invalid range. can select text again:

var range = document.createrange(); //creade range object. not ie compatible! range.setstart(sel[0][0], sel[0][1]); //load start our variable range.setend(sel[1][0], sel[1][1]); //load end var s = window.getselection(); s.removeallranges(); //i'm not sure necessary s.addrange(range);

then can text:

alert("selected: "+s.tostring());

javascript jquery textselection

No comments:

Post a Comment