13

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

John
  • 1
  • 13
  • 98
  • 177
endy
  • 3,872
  • 5
  • 29
  • 43

2 Answers2

31

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);
John
  • 1
  • 13
  • 98
  • 177
Phil McCullick
  • 7,175
  • 2
  • 29
  • 29
  • @phil mccull +1 for the answer. what if you only have to insert the text in that div only and not anywhere else in the document, when 'wrap' is clicked? – Neha Choudhary Sep 04 '14 at 05:26
  • got the answer to my question from the link : http://stackoverflow.com/a/8340432/1407434, updated fiddle : http://jsfiddle.net/tM3mA/38/ – Neha Choudhary Sep 04 '14 at 05:46
  • I am very late to the party, but I have a question - when I change the line `var newNode = ..` to `var newNode = document.createElement('wbr');` it doesn't work - and the cursor is before the tag .. you can check this in the console when you inspect the element, see http://jsfiddle.net/7zd6r79d/ How can I get the cursor after the tag? – Betty St Mar 31 '16 at 20:54
  • I have checked it to my case with TEXT_NODE (document.createTextNode('\r\n');) and caret is finally added to the end of element in hiarchy above :( – Václav Švára May 03 '20 at 14:05
1

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

Saket Patel
  • 6,573
  • 1
  • 27
  • 36