If an element can contain the caret, you can move the caret to that element using:
$([selector]).focus();
$([selector]).select(); //include this line if '.focus()' alone isn't working
Although I don't think the li
element can contain the caret, but it's inside an editable div
as you say, so maybe then it can. Couldn't say for sure without knowing the exacts of your situation.
... After trying really hard for a really long time with the fiddle from the first comment, I'm really starting to believe that it's just not possible. I eventually got to this, but aren't getting any further.
(Original caret positioning code by Tim Down.)
UPDATE
After even longer and ever harder trying (by the OP, I had given up), finally a solution was found.
Yes, it's pretty hacky, and not IE9- compatible, but it does the job:
$(window).on('load',function(){
$('#addListBtn').click(function(){
$('div.input').append('<ul><li><div id="insertedList"> </div></li></ul>');
if (setCaret('insertedList')) {$('#insertedList').remove();} //don't remove until setCaret() has fully executed
});
function setCaret(id) {
var range = document.createRange();
range.setStart(document.getElementById(id).childNodes[0],0);
range.collapse(true);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
return true;
}
});
.input {border: 1px solid #ccc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="addListBtn">Insert List</button><br /><br /> <!--FOR TESTING ONLY!-->
<div class="input" contenteditable="true">
Some text that's already in the div.
</div>
(
fiddle: http://jsfiddle.net/nsf0rt51/10/)
- This code first appends the list:
<ul><li><div id="insertedList"></div></li></ul>
. Notice the dummy div
inside the li
.
(This is done, because in order to set the caret, the element must have an ID and must have some content. By using a dummy div
, we can just remove that div afterwards when the caret is set, and what remains is a clean list.)
- Next, the caret is set to the start of the dummy
div
. I put the code for this inside a standard function that is invoked from inside the click-handler. I did it this way, so that the function can be invoked from multiple places (maybe you want to insert other things that also need focus upon insertion).
- Finally, the dummy
div
is removed from the DOM, leaving us with a clean <ul><li></li></ul>
, with the caret blinking inside it.
Notice that $([selector]).focus();
isn't necessary anymore, because the focusing is happening automatically when the caret is set.
If you find that the code isn't working however, try and put $('div.input').focus();
right after the append line, maybe it will help.