Reputation: 2233
Heres a jquery code, to set the cursor position in content editable div to position 10
var range,selection; var contentEditableElement = $("div#editMe");
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(true);
range.setStart(contentEditableElement,0);
range.setEnd(contentEditableElement,10);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
But this ones not working. Whats the problem . ??
Upvotes: 3
Views: 724
Reputation: 7303
Here is a working example. It doesnt seems to work if I only put text inside the div, I have to put every single character each in an element. Also notice that you have to use .get(0) on a jquery object to actually get a dom object to use with range.setStart and range.setEnd.
html:
<div id="editMe">
<span>a</span><span>b</span><span>c</span><span>d</span><span>e</span><span>f</span><span>g</span><span>h</span><span>i</span><span>j</span><span>k</span><span>l</span><span>m</span><span>n</span>
</div>
<button onclick="do_select()">
select characters
</button>
js:
function do_select()
{
var element = $("div#editMe").get(0);
var range = document.createRange();
range.collapse(true);
range.setStart(element,0);
range.setEnd(element,10);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
Upvotes: 2