Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting caret after an inserted node

Tags:

javascript

So I have a method that takes a tag and wraps the selected text in that tag.

function wrap(tag) 
{               
    var sel, range;
    if (window.getSelection)
    {
        sel = window.getSelection();
        if (sel.rangeCount)
        {
            range = sel.getRangeAt(0);
            var selectedText = range.toString();
            range.deleteContents();
            range.insertNode(document.createTextNode('['+tag+']'+selectedText+'[/'+tag+']'));                            
        }
    } 
}

This issue with this however, is after it's done wrapping the text and inserting the node the caret (where they are typing) is placed BEFORE the inserted text.

Is there such way to insert the text and have the caret remain at the end of it?

Please note i'd prefer if this could be done without the use of jQuery or any other library. I only need it to work in webkit (Safari).

like image 460
endy Avatar asked Mar 22 '12 18:03

endy


2 Answers

You can use the range.setStartAfter and range.setEndAfter methods to set the start and end points to the point directly after your new node. I setup a jsfiddle example here: http://jsfiddle.net/phil_mcc/tM3mA/

//move the caret
range.setStartAfter(newNode);
range.setEndAfter(newNode); 
sel.removeAllRanges();
sel.addRange(range);
like image 119
Phil McCullick Avatar answered Oct 12 '22 22:10

Phil McCullick


do this after inserting the node to the range range.collapse(false); this will change position of selection range to the end of the range, so my guess is it should set the cursor at end position

like image 44
Saket Patel Avatar answered Oct 12 '22 22:10

Saket Patel