2

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 ?

Community
  • 1
  • 1
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121
  • Your code snippet has an error. Are you sure you don't wanna edit that for us to know exactly what the real error is? (of course if it's the error in the snippet, that's your first clue, probably?) – Cedric Ipkiss May 01 '17 at 21:07

1 Answers1

2

instead of passing in a jquery object, pass in a node ref.

IE.

$(document).ready(function(){
 var node = document.getElementById('test');
 focusAndPlaceCaretAtEnd(node);
});

Those range functions apparently arent smart enough to figure out when they've been passed a jquery object.

http://jsfiddle.net/g9Lxkvbb/1/

Rooster
  • 9,954
  • 8
  • 44
  • 71
  • idk. maybe you have some css on your site thats not in the fiddle. Otherwise, seems like it would have to be some other code. – Rooster May 01 '17 at 21:44