Tuesday 15 February 2011

javascript - How to set cursor at given postion in editable div -



javascript - How to set cursor at given postion in editable div -

i have div

<div id="user_status" class="status expanddiv" onkeyup="username_search('new','user_status');" contenteditable="true" data-text="what's on mind?..."> text goes here. </div>

when username_search function call, through cursor @ 0 postion. while need remain cursor @ actual postion. can cursor postion before phone call function. not able set.

does ant 1 have solution this?

if using chrome or firefox below code works accomplish task. code not tested in ie or safari.

the setcaretposition function want think

class="snippet-code-js lang-js prettyprint-override">function getcaretposition(editablediv) { var caretpos = 0, containerel = null, sel, range; if (window.getselection) { sel = window.getselection(); if (sel.rangecount) { range = sel.getrangeat(0); if (range.commonancestorcontainer.parentnode == editablediv) { caretpos = range.endoffset; } } } homecoming caretpos; } function setcaretposition(ctrl, pos) { if (window.getselection) { pos = (ctrl.textcontent.length > pos ? pos : ctrl.textcontent.length); var selection = window.getselection(); var range = document.createrange(); range.selectnodecontents(ctrl.childnodes[0]); range.endoffset = pos; selection.removeallranges(); selection.addrange(range); selection.collapse(ctrl.childnodes[0], pos); } } function username_search(st,str) { var ctl = document.getelementbyid('user_status'); var pos = getcaretposition(ctl); document.getelementbyid("user_status").textcontent = "dsdssadsadasdffstjdyjdrtyurtystseryds"; setcaretposition(ctl,pos); } class="snippet-code-html lang-html prettyprint-override"><div id="user_status" class="status expanddiv" onkeyup="username_search('new','user_status');" contenteditable="true" data-text="what's on mind?..."> text goes here. </div>

javascript jquery

No comments:

Post a Comment