Cereal Killer
Cereal Killer

Reputation: 3414

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.

Upvotes: 4

Views: 5195

Answers (2)

sk8terboi87  ツ
sk8terboi87 ツ

Reputation: 3457

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
    }
}

Upvotes: 5

Eisa Qasemi
Eisa Qasemi

Reputation: 826

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);

  }

Upvotes: 8

Related Questions