Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cursor to the end of contenteditable div

I am trying to set the cursor to the end of next/prev contenteditable tag if the current one is empty, but when I set focus it adds focus to the begining of the text and not end Tried almost all solution on SO but none seemed to work for me. Here the simple code I am trying

HTML CODE

<div id = 'main'>
<div id = 'n1' contenteditable=true> Content one</div>
<div id = 'n2' contenteditable=true> Content 2</div>
<div id = 'n3' contenteditable=true> Content 3</div>
<div id = 'n4' contenteditable=true> Content 4</div>

JS CODE

$('#main div').keydown(function(){
if(!$(this).text().trim()){
    $(this).prev().focus();
   //setCursorToEnd(this.prev())
    }
});


function setCursorToEnd(ele)
  {
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(ele, 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    ele.focus();
  }
like image 324
Ross Avatar asked Nov 22 '12 13:11

Ross


2 Answers

you are using jQuery and getting the element from jQuery. You must convert it into a native DOM element (via the jQuery-get Function) to use the "setCurserToEnd"-Function:

your method-call:

setCursorToEnd(this.prev());

working solution:

setCursorToEnd($(this).prev().get(0));

see the updated fiddle: http://jsfiddle.net/dvH5r/4/

like image 179
hereandnow78 Avatar answered Sep 30 '22 06:09

hereandnow78


You were pretty close, the only problem is that prev() returns a jQuery object, whereas you want to pass the actual DOM element to setCursorToEnd()

Finished product: http://jsfiddle.net/B5GuC/

*Note: this works even if the above div element is empty. Vanilla js ftw.

$('#main div').keydown(function(){
    if(!$(this).text().trim()){
        $(this).prev().focus();
        setCursorToEnd(getPrevSib(this));
    }
});

function setCursorToEnd(ele){
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(ele, 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
}

function getPrevSib(n){
    //gets prev sibling excl whitespace || text nodes
    var x=n.previousSibling;
    while (x && x.nodeType!=1){
          x=x.previousSibling;
    }
    return x;
}
like image 30
gkiely Avatar answered Sep 30 '22 05:09

gkiely