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


i trying create text editor. users can insert html code there. there toolbar. when user clicks 'add code' button, want <code></code> text inserted cursor @ middle of start , end tag.

i have got following code insert text @ 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 = (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 code desired <code></code> inserted before cursor. there way use code achieve following :

<code> + cursor + </code>

yes, it's possible.

since function moves caret end of inserted string, need move few characters (7 in case). i'd modify function include param specify number of characters want move caret by.

 function insertatcaret(areaid, text, caretoffset) { 

then change part calculate caret position to

strpos = strpos + text.length + caretoffset; 

and when call function, so:

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

it should work. here's codepen demonstrate.

of course, may or may not want enhance more robust checks, ensuring caretoffset negative, or max number of characters moves caret number of characters in added text.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -