Inserting two strings with the cursor in the middle of the two strings with JavaScript

72 Views Asked by At

I am trying to create a text editor. Users can insert html code there. There is a toolbar. When user clicks 'Add Code' button, I want that a <code></code> text will be inserted with the cursor at the middle of start and end tag.

I have got the following code to insert any text at the cursor position :

function insertAtCaret(areaId,text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
    "ff" : (document.selection ? "ie" : false ) );
if (br == "ie") { 
    txtarea.focus();
    var range = document.selection.createRange();
    range.moveStart ('character', -txtarea.value.length);
    strPos = range.text.length;
}
else if (br == "ff") strPos = txtarea.selectionStart;

var front = (txtarea.value).substring(0,strPos);  
var back = (txtarea.value).substring(strPos,txtarea.value.length); 
txtarea.value=front+text+back;
strPos = strPos + text.length;
if (br == "ie") { 
    txtarea.focus();
    var range = document.selection.createRange();
    range.moveStart ('character', -txtarea.value.length);
    range.moveStart ('character', strPos);
    range.moveEnd ('character', 0);
    range.select();
}
else if (br == "ff") {
    txtarea.selectionStart = strPos;
    txtarea.selectionEnd = strPos;
    txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}

With this code my desired <code></code> is inserted before the cursor. Is there any way to use the code to achieve the following :

<code> + Cursor + </code>

1

There are 1 best solutions below

3
On BEST ANSWER

Yes, it's possible.

Since your function already moves the caret to the end of the inserted string, you just need to move it back by a few characters (7 in this case). I'd modify the function to include a param to it to specify the number of characters I want to move the caret back by.

 function insertAtCaret(areaId, text, caretOffset) {

Then change the part where you calculate the caret position to

strPos = strPos + text.length + caretOffset;

And when you call your function, do it like so:

insertAtCaret('my-textarea', '<code></code>', -7);

It should work. Here's a codepen to demonstrate.

Of course, you may or may not want to enhance it with more robust checks, like ensuring that caretOffset is always negative, or that the max number of characters it moves the caret back by is the number of characters in the added text.