I have this JSFiddle where I try to implement what is described in this post. However, surprisingly my code won't work and I just can't make out why.
Just in case, I place the same code here in stackoverflow.
$(document).ready(function(){
focusAndPlaceCaretAtEnd($('#test'));
});
function focusAndPlaceCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" contenteditable="true" placeholder="">
Focus and place the cursor to the end
</div>
Most probably, there is some stupid error in my code. Can anyone save my brains providing a hint on this ?