Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cursor at the end of content editable

I have a simple content editable that contains text with tags... when a tag is inserted the word is replaced with a span inside it...

<div contenteditable=true>
      text text text <span class="tag">tag</span> 
</div>

This is the result (when user press space the tag is replaced with a span containing the tag's text; this happens on keyup)

Then I need to place the cursor at the end of the content editable (outside the span) in order to let the user continue typing...

I've been able to move the cursor at the end but only inside the span...

I use rangy.

like image 553
Cereal Killer Avatar asked Oct 20 '25 05:10

Cereal Killer


2 Answers

this may work

function moveCursorAtTheEnd(){
    var selection=document.getSelection();
    var range=document.createRange();
    var contenteditable=document.querySelector('div[contenteditable="true"]');

    if(contenteditable.lastChild.nodeType==3){
      range.setStart(contenteditable.lastChild,contenteditable.lastChild.length);
    }else{
      range.setStart(contenteditable,contenteditable.childNodes.length);
    }
    selection.removeAllRanges();
    selection.addRange(range);

  }
like image 187
h8n Avatar answered Oct 22 '25 19:10

h8n


This works much simpler as well https://gist.github.com/al3x-edge/1010364

function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}
like image 21
sk8terboi87 ツ Avatar answered Oct 22 '25 19:10

sk8terboi87 ツ