Search code examples
javascriptdomcursor

How do I use JavaScript to change the position of a cursor and then place new content at it?


I am using JavaScript to create a very simple code that inserts bulletin board codes into a textarea when you click on a button.
The code I wrote works ok, however, I would like to be able to place the new tags at the cursor instead of at the end of the text, and then keep the cursor in the middle of the new tags.
For example: currently, when a user clicks b, then u, then s, it displays as [b][/b][u][/u][s][/s]. I would like to be able to do something like [b][u][s]^[/s][/u][/b] where ^ is the cursor. Is there any easy way to do this?

<script type="text/javascript">

   function addTag(prefix, suffix){

       texteditor = document.getElementById("texteditor");

       texteditor.innerHTML += '[' + prefix + ']' + '[' + suffix + ']';

}
</script>

<ul class="wysiwyg">
    <li><a href"#" title="Bold" class="bold" onclick="addTag('b', '/b'); return false;"></a></li>
    <li><a href"#" title="Underline" class="underline" onclick="addTag('u', '/u'); return false;"></a></li>
    <li><a href"#" title="Strike Through" class="strikethrough" onclick="addTag('s', '/s'); return false;"></a></li>
    <li><a href"#" title="Italicize" class="italics" onclick="addTag('i', '/i'); return false;"></a></li>
</ul>

Solution

  • First, to change the text inside a textarea, use its value property rather than innerHTML, which in most browsers will not work after the user has interacted with the textarea. Also, you should declare variables such as texteditor in your example) with var (or let in ES6).

    As to your actual issue, you need to use the selectionStart and selectionEnd properties of the textarea. if you use jQuery, you may use this plug-in (written by me) useful: it has a surroundSelectedText method.

    $("#texteditor").surroundSelectedText("<b>", "</b>");
    

    Otherwise, here is some code that will do it except in IE <= 8, which does not support the selectionStart and selectionEnd properties. For old IE support, I'd suggest taking a look at the source code of my jQuery plug-in.

    Demo: http://jsfiddle.net/mLkNV/

    Code:

    function addTag(prefix, suffix) {
        var texteditor = document.getElementById("texteditor");
        var val = texteditor.value;
        var start = texteditor.selectionStart;
        var end = texteditor.selectionEnd;
    
        // Insert the prefix and suffix
        texteditor.value = val.slice(0, start) +
            '[' + prefix + ']' + val.slice(start, end) + '[' + suffix + ']' +
            val.slice(end);
    
        // Reset the selection
        texteditor.selectionStart = start + prefix.length + 2;
        texteditor.selectionEnd = texteditor.selectionStart + (end - start);
    }