Inserting at the cursor using JavaScript

Posted in: Development

NOTE: I’ve released a set of JavaScript Quicktags (that implement this technique) under the LGPL license. Please look at this code as it has a variety of enhancements and bug fixes.

I discovered a real JavaScript gem in PHPMyAdmin this morning. They have code that inserts content into a <textarea> at the cursor position instead of just at the beginning/end of the content. This is something I thought wasn’t possible - I’m quite pleased I was wrong.

I’ll be glad to see this code spread quickly to web forms that use buttons to aid in styling text and inserting image and link tags. WordPress and other blog and web forum packages would really benefit from this. (PHPMyAdmin is GPL, so any other GPL app should be able to use their code directly with attribution).

Here is a quick look at a generic version of the technique:

function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == ‘0′) {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
// calling the function
insertAtCursor(document.formName.fieldName, ‘this value’);

I guess when the mouse leaves the textarea, it still has a cursor position left over. This code uses that position just as you’d want it to.

Popularity: 43% [?]

Posted June 2nd, 2003 @ 3:55 PM

124 Replies

  1. Justin adds this Comment:

    Thanx for posting this, couldn’t find it anywhere else on the net.

    Nice one!

    January 15th, 2004 at 6:33 am

  2. Noah Spurrier adds this Comment:

    Now, how do I delete at the cursor position? tricky…

    March 4th, 2004 at 5:40 pm

  3. Alex adds this Comment:

    You just manipulate the string using the cursor position as a base, it isn’t hard.

    March 4th, 2004 at 5:42 pm

  4. brian adds this Comment:

    i tried this code - and it just appends the text to the end of a netscape textarea. is that how it is supposed to work? i can’t find code that works for both IE and NS. this, sadly, is one of the many that do not work in NS.

    Please let me know if there’s a way around this.

    March 15th, 2004 at 1:09 pm

  5. Alex adds this Comment:

    Depends on your version of Netscape I guess. Current versions insert at the cursor - old versions and unsupported browsers insert at the end.

    March 15th, 2004 at 2:03 pm

  6. eko adds this Comment:

    Thank’s man…:)

    April 22nd, 2004 at 7:56 am

  7. Maus adds this Comment:

    thank you very much!

    April 26th, 2004 at 8:11 am

  8. anna adds this Comment:

    I tried on Netscape 7.0, it doesn’t seem to work… ;(

    April 27th, 2004 at 6:47 am

  9. Tom adds this Comment:

    I’ve used the code listed here:

    In an IE only environment to style input.

    function format_sel(v) {
    var str = document.selection.createRange().text;
    document.PostTopic.Message.focus();
    var sel = document.selection.createRange();
    sel.text = “[” + v + “]” + str + “[/” + v + “]”;
    return;
    }

    April 29th, 2004 at 12:11 pm

  10. leonard adds this Comment:

    For those of you interested in some history:
    http://randomfoo.net[...]yevents.html http://randomfoo.net[...]etselection/

    I started working on trying to do DOM ranging in Mozilla back in 2000. Finally fixed at the beginning of 2003. (hooray)

    Err, so that’s after the last release of NS7 I think (might be in NS7.1, definitely in the upcoming NS7.2) and Moz 1.3+.

    May 3rd, 2004 at 1:18 am

  11. Michael adds this Comment:

    Great thanx to you! It helped me very much.

    May 25th, 2004 at 10:53 am

  12. (a different) Alex adds this Comment:

    Wow great little piece of code!
    Been looking for this all over
    Thanks

    May 26th, 2004 at 10:15 am

  13. Barry adds this Comment:

    Doesn’t work in Opera either.

    May 27th, 2004 at 8:20 pm

  14. Kryz adds this Comment:

    Thanks for posting the code here, alex.
    Before I forghet to give something in return: this script works in my Mozzilla 1.6 browser.
    Great thing for I have spent days wondering why some similar script involving getSelection stuff did not work.
    I am using a homebrew weblog and yet have to create my own admin panel to make publishing my articles-with-HTML a little more comfortable than by using phpmyadmin… ;-)

    June 30th, 2004 at 3:21 am

  15. Prab adds this Comment:

    This is code is very useful. Thankyou so much

    June 30th, 2004 at 11:56 am

  16. Carthik adds this Comment:

    I was looking for a solution to the problem that in Firefox 0.9, with wordpress 1.2, the view changes to the top of the post entry field and ended up here.

    The cursor does not jump, but the scrollbar at the text entry field goes right to the top and I have to scroll down to see where I was at.

    I’d appreciate a solution.

    July 6th, 2004 at 6:06 pm

  17. Alex adds this Comment:

    I don’t think there is a solution. Setting focus to the field seems to scroll the content to the top, the positioning the cursor doesn’t scroll the content accordingly. You can hit the arrow key and it will jump back down to where the cursor is.

    July 6th, 2004 at 6:10 pm

  18. mark adds this Comment:

    Four hours searching… Finally!! something that works in Mozilla! Pity about Firefox 0.9 but it’s got me out of trouble for now… You’re a champion.

    July 16th, 2004 at 1:34 pm

  19. holle adds this Comment:

    Hi, this is exactly what i’m looking for. But I have no understanding of JavaScript. Could anyone please tell me how to use this to insert for instance a BR tag into the textarea?

    Thx

    July 19th, 2004 at 9:59 am

  20. Josh Dunkelman adds this Comment:

    Thanks for the code! I’m using it to quicken the process of answering feedback reports. We usually get the same reports over and over again.

    October 18th, 2004 at 3:02 pm

  21. Ken adds this Comment:

    I think I found a solution to that problem regarding the comment on July 6th by Alex:

    Use save and reset the scrollTop property of the textarea object.

    November 9th, 2004 at 3:12 pm

  22. Alex adds this Comment:

    Yep, this was actually fixed in my Quicktags already.

    November 9th, 2004 at 6:28 pm

  23. John Owens adds this Comment:

    Just thought I’d let you know, in case you weren’t already aware, this page is now referenced in the source of the BBCode extension for Firefox & Mozilla, where I found it while learning to make extensions (& brushing up on my rusty JavaScript) and need to do exactly this. Perhaps I’ll post back here again when/if I’ve got something workable to share.

    December 4th, 2004 at 4:29 am

  24. Trond Nilsen adds this Comment:

    Maybe it’s trivial, but I’ve added a bit to this snippet such that the added text becomes highlighted / selected once inserted. :)

    function insertAtCursor(myField, myValue)
    {
    //IE support
    if (document.selection)
    {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
    sel.moveStart(’character’, -myValue.length);
    sel.select();
    }

    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == ‘0′)
    {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value =
    myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);
    myField.selectionStart = startPos;
    myField.selectionEnd = startPos + myValue.length;
    }

    //Anyone else.
    else
    {
    myField.value += myValue;
    }
    }

    December 11th, 2004 at 7:55 pm

  25. Alex adds this Comment:

    If you do that, you can’t just keep typing or you’d overwrite the inserted text.

    December 11th, 2004 at 8:42 pm

  26. David adds this Comment:

    Anyone know how insert text before and after a highlighted/selected text?

    December 20th, 2004 at 3:31 pm

  27. Alex adds this Comment:

    Um, that is what this does…

    December 20th, 2004 at 3:58 pm

  28. David adds this Comment:

    function insertAtCursor(myField, myValue1, myValue2) {
    //IE support
    if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue1+sel.text+myValue2;
    myField.focus();
    }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == ‘0′) {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
    + myValue1 + myField.value.substring(myField.selectionStart, myField.selectionEnd)
    + myValue2 +myField.value.substring(endPos, myField.value.length);
    myField.selectionStart = startPos+3;
    myField.selectionEnd = endPos + myValue1.length + startPos;
    myField.focus();
    } else {
    myField.value += myValue1+myValue2;
    }
    }

    Maybe this can help somebody, I made this changes to use this:
    onClick”insertAtCursor(document.noticia.cuerpo, ‘‘,’‘)”

    December 21st, 2004 at 12:28 pm

  29. Alex adds this Comment:

    You should look at the Quicktags code - it already had this functionality.

    December 21st, 2004 at 12:31 pm

  30. David adds this Comment:

    Thanks!, you make my work easier!

    December 21st, 2004 at 12:45 pm

  31. Richard adds this Comment:

    Not sure what I’ve achieved, but I used the IE support bit of code from this site (thanks Alex) and combined it with something else for Mozilla. I think it has the same limitations, but I have combined a ‘put tags around selected text’ script as well. Maybe I’ve just condensed the code for both? - not sure.

    Anyway it can be found HERE.

    Cheers,
    R

    December 21st, 2004 at 4:08 pm

  32. Alex adds this Comment:

    How is this any different than my JS Quicktags?

    December 21st, 2004 at 4:18 pm

  33. Richard adds this Comment:

    Ahhhh apologies. I hadn’t seen that page. Impressive stuff. Feel free to delete my post….because of course you have ever right to. In Google this page ranked higher than your JS Quicktags on my search. Oh dear, I could have saved 2 days. Never mind - I’ve learned a lot about JS.

    December 21st, 2004 at 4:40 pm

  34. Alex adds this Comment:

    This is why I have the note at the top of the post…

    NOTE: I’ve released a set of JavaScript Quicktags (that implement this technique) under the LGPL license.

    December 21st, 2004 at 4:41 pm

  35. Richard adds this Comment:

    A fair point. I’d missed that bit and went straight for the code. Sorry again.

    December 21st, 2004 at 4:54 pm

  36. Heleen adds this Comment:

    I was wondering how to get it working from a pop-up window, to a normal window with the textarea (smiley idea from tagboard).

    December 30th, 2004 at 6:33 am

  37. Heleen adds this Comment:

    I found out for IE:

    December 30th, 2004 at 6:58 am

  38. spilo101 adds this Comment:

    I have a simple script that checks the key and converts it to different character. With IE code worked fine.. as event.keyCode = “somevalue” works there fine.. but in Mozilla type browsers event.which = “somevalue” does not work. so I took different approach. YOur script is very helpful, i would like to thank you. There is one thing that i want to knwo, though.. when I insert character into text (somwhere in between, after moving down with arrow) the cursor jumps to the end of text. Is it possible to leave at the point where it was entered? I mean after the character entered..
    thank you again very much.

    December 31st, 2004 at 10:41 pm

  39. Alex adds this Comment:

    I don’t think my Quicktags display this behavior, why don’t you borrow that code?

    January 1st, 2005 at 10:53 am

  40. spilo101 adds this Comment:

    I posted my script but it was deleted..

    January 2nd, 2005 at 4:23 pm

  41. Alex adds this Comment:

    This isn’t a support forum. :)

    January 2nd, 2005 at 4:26 pm

  42. Moondog adds this Comment:

    That last snippet of code David posted December 20, 2004 @ 3:58 pm works great but I noticed one issue that maybe some one can help me out with.

    If you click to insert tags where the curser is flashing it inserts the tags fine. But if you highlight text then lick it, it wraps the tags around the text properly but the curser doesn’t seem to focus at the end of the text so if you type anything it overwrites it all.

    January 2nd, 2005 at 7:03 pm

  43. Alex adds this Comment:

    Like I told David: why don’t you use the Quicktags? They already do this…

    January 2nd, 2005 at 8:12 pm

  44. James Hall adds this Comment:

    Thank you very much. I knew it was possible, I just couldn’t find the mothods and properties anywhere else.

    January 4th, 2005 at 7:35 am

  45. Tam C adds this Comment:

    Thanks, it works great - now, I can relax for the rest of the day and thanks to you…
    I have to create a UI that assists a merchant to compose an email message. For example, a merchant can insert a predetermined line of text into the messageTextBox at a desired position with a click on a specified control

    January 4th, 2005 at 12:37 pm

  46. Lyon Blecher adds this Comment:

    Great Code, been trying to get my


    inserted into the WYSIWYG editor without having to select the text, using execCommand, manually with the mouse. so used your code to select a textrange from the cursor, of a ” “, to create the effect of a selection!!
    Thanx :)

    January 7th, 2005 at 3:35 am

  47. Joho adds this Comment:

    Nice code… THX

    January 7th, 2005 at 8:47 am

  48. Jason adds this Comment:

    This code was exactly what I was looking for. Thanks!

    January 7th, 2005 at 10:11 am

  49. Dean adds this Comment:

    Great bit of code. Is this also covered under the LGPL? And any specific restrictions for commercial use?

    January 8th, 2005 at 9:15 am

  50. Alex adds this Comment:

    Why don’t you just use the Quicktags code as a base (which has an updated version of this code anyway).

    January 8th, 2005 at 3:46 pm

  51. Kevin adds this Comment:

    Why isn’t there any offical support for this stuff? I search google and a blog is the only thing capable of helping me? Thanks a lot though eh, good stuff.

    January 14th, 2005 at 11:27 am

  52. Keith Kikta adds this Comment:

    I found what Trond Nilsen came up very helpful but i needed the cursor to to go to the end of the inserted text not highlight. Here is my slight modification for this change.

    function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
    var temp;
    myField.focus();
    sel = document.selection.createRange();
    temp = sel.text.lenght;
    sel.text = myValue;
    if (myValue.length == 0) {
    sel.moveStart(’character’, myValue.length);
    sel.moveEnd(’character’, myValue.length);
    } else {
    sel.moveStart(’character’, -myValue.length + temp);
    }
    sel.select();
    }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == ‘0′) {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
    myField.selectionStart = startPos + myValue.length;
    myField.selectionEnd = startPos + myValue.length;
    } else {
    myField.value += myValue;
    }
    }

    January 18th, 2005 at 2:50 pm

  53. AlexM adds this Comment:

    I modified this awesome function so that it works also for the BACKSPACE at cursor:

    function backAtCursor(myField) {

    if (document.selection) {

    myField.focus();

    sel = document.selection.createRange();

    if(sel.text.length > 0) {
    sel.text=”;
    }else{
    sel.moveStart(’character’,-1);
    sel.text=”;
    }

    sel.select();

    }else if (myField.selectionStart || myField.selectionStart == ‘0′) { //MOZILLA/NETSCAPE support
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;

    myField.value = myField.value.substring(0, startPos-1) + myField.value.substring(endPos, myField.value.length);
    myField.selectionStart = startPos-1;
    myField.selectionEnd = startPos-1;
    myField.focus();
    } else {
    myField.value=myField.value.substr(0,(myField.value.length-1));
    myField.focus();
    }

    }

    You can see the working example at the virtual on screen English keyboard:

    www.enetplanet.com/kb_en/

    Why on screen English keyboard? Because some people can not type on hardware keyboards due to physical challenges.

    February 15th, 2005 at 5:43 am

  54. Steve Collyer adds this Comment:

    I’ve released a small Javascript library, under the GPL, that performs real-time text box syntax checking and enforcement, which uses the technique discussed here:

    Synforce

    IE and Mozilla support only at the moment.

    February 22nd, 2005 at 2:06 pm

  55. Mike adds this Comment:

    Thanks a lot for this most useful piece of code !

    March 8th, 2005 at 3:23 pm

  56. Jeff adds this Comment:

    Hi, awesome script - thanks. I was playing around with the example page:

    http://alexking.org/[...]s/index.html

    and noticed that with IE when I highlight some text and click a tag it surrounds it as expected with the choosen tags but the cursor does not return to the textarea so if I type something the previously selected text and the new tags that surround it get overwritten. Otherwise, everything seems to work as expected, thanks again!

    April 17th, 2005 at 6:38 pm

  57. dan clift adds this Comment:

    Hi

    Thanks so much for this Ive been scratching my head and hammering google for a few days now and couldnt get it to work. My editable website / blog / forum / etc etc will soon be finished.

    thanks again
    dano

    April 22nd, 2005 at 9:17 am

  58. Bart adds this Comment:

    Is this code still being maintained? I noticed there are some quirks in how this works in the latest version of Safari, which has pretty solid JavaScript support especially with the new 1.3 version.

    May 3rd, 2005 at 11:34 am

  59. Alex adds this Comment:

    Haven’t tested on 1.3, but all earlier versions of Safari don’t support getting selection from a TEXTAREA.

    The JS Quicktags are actively developed.

    May 3rd, 2005 at 11:36 am

  60. Bart adds this Comment:

    What about IE for Mac? I know it’s not even shipping in Tiger, but the bug with the close tag buttons not turning back into open tag buttons is pretty significant.

    May 3rd, 2005 at 1:25 pm

  61. Alex adds this Comment:

    IE for Mac is definitely not supported - not much a developer can do to support a browser that doesn’t work properly.

    May 3rd, 2005 at 4:32 pm

  62. Kim adds this Comment:

    Great code, works just splendid. Well that is with IE.. not in FireFox.

    Whenever i have inserted my quicktag in to the textarea, the cursor loses focus and dissapears.

    How would one come about as to solving that thing?

    May 17th, 2005 at 5:58 am

  63. Alex adds this Comment:

    Sorry, never heard of that problem nor can I reproduce it.

    May 17th, 2005 at 8:49 am

  64. Kim adds this Comment:

    ah well.. just thought you should know.

    May 17th, 2005 at 11:05 am

  65. Alex adds this Comment:

    Maybe you can post more information in the JS Quicktags support forum so we can look into it futher.

    May 17th, 2005 at 1:47 pm

  66. Kim adds this Comment:

    i used a snipplet found in js_quicktags.js and now it works perfectly in IE and FF.

    this is the snipplet.

    function edInsertContent(myField, myValue) {
    //IE support
    if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
    myField.focus();
    }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == ‘0′) {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);
    myField.focus();
    myField.selectionStart = startPos + myValue.length;
    myField.selectionEnd = startPos + myValue.length;
    } else {
    myField.value += myValue;
    myField.focus();
    }
    }

    once again, great code :)

    May 18th, 2005 at 1:02 am

  67. Eric adds this Comment:

    Thanks!

    This is perfect :)

    May 24th, 2005 at 8:35 am

  68. Vivin adds this Comment:

    Thanks for this piece of code :) Works like a charm!

    May 25th, 2005 at 4:01 pm

  69. Chuck adds this Comment:

    Thanks so much for this code snippit. Used to have an iframe but good old SP2 of XP threw up on it - worked great before. But this allows me to remove the whole darn iframe!!! thanks so much.

    June 19th, 2005 at 3:22 pm

  70. Josh adds this Comment:

    Brilliant. An answer to years of searching :) AND it’s easily customizable!! Thanks so much!

    July 6th, 2005 at 7:54 am

  71. roja adds this Comment:

    This code really worx well not only for textarea but for a simple textbox when u need to append a constant while clicking a button…

    Thanx

    August 2nd, 2005 at 1:29 am

  72. Mike adds this Comment:

    I was trying to delete a character in a textbox based off the cursor position from a virtual keyboard and found this can be a bit tricky. FF is pretty straight forward but in IE I struggled with it for a bit so I thought I would post the code to help anyone else who might want to do this.
    // set focus to element
    Keyboard_ActiveTextElement.focus();
    // get empty selection range since its just a cursor
    var sel = document.selection.createRange();
    // move the start to the location before
    sel.moveStart(’character’,-1);
    // keep the end point the same
    sel.moveEnd(’character’,0);
    // select based upon new start and end
    sel.select();
    // set the selected text to nothing
    sel.text = ”;
    // select one more time so that cursor reappears
    sel.select();

    August 10th, 2005 at 7:51 am

  73. MIBO adds this Comment:

    This code really worx well not only for textarea but for a simple textbox when u need to append a constant while clicking a button…

    August 15th, 2005 at 2:27 am

  74. Hari adds this Comment:

    hey!!! worked for me!!! thanks!

    September 22nd, 2005 at 11:27 pm

  75. mix adds this Comment:

    On FireFox 1.0.7 myField looses focus when clicking on button, so adding myValues at the end on second click. Here was my solution added to MOZILLA part:


    myField.value = myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);

    myField.selectionStart = startPos + myValue.length;
    myField.selectionEnd = endPos + myValue.length;
    myField.focus;

    Hope it helps someone…

    October 11th, 2005 at 11:34 am

  76. Alex adds this Comment:

    That’s strange, I have no such problem in Firefox 1.0.7, nor has anyone else let me know they have seen this.

    October 11th, 2005 at 2:22 pm

  77. Allen Schmidt, Jr adds this Comment:

    Hey, thanks! I could not find this anywhere else!

    October 21st, 2005 at 11:18 am

  78. Jeff Barczewski adds this Comment:

    Thanks for figuring this out and posting to the web, I was having trouble trying to figure all this out in a portable way.

    November 20th, 2005 at 11:25 am

  79. ben jackson adds this Comment:

    This is great, a real time saver, I could have been trawling the web and my javascript books for hours dayws weeks months fo rthis.

    I modified it slightly for those wanted to add text around a selection rather than replacing the selection.

    I know this is probably somewhere else in this blog, but here it is anyway.

    [ take a look at the JS Quicktags (linked, in bold, at the top of this post) for code examples - ak ]

    December 7th, 2005 at 1:07 pm

  80. Marc Baber adds this Comment:

    On a related note, I just wanted to set the cursor position of a TEXT item to the end of the initial (VALUE=) string at onLoad time. Turns out you can just set the value attribute equal to the value attribute, thus:

    document.myform.mytextitem.value = document.myform.mytextitem.value;

    Looks kind of pointless, but it works!

    December 13th, 2005 at 1:57 am

  81. Stefan Engstgrom adds this Comment:

    I use a modified version of this to allow text input from a different frame, but the IE portion is giving me trouble (mozilla part works fine).

    cfocus=parent.left.cfocus;
    //IE support
    if (parent.left.document.selection) {
    cfocus.focus();
    sel = parent.left.document.selection.createRange();
    sel.text = myValue;
    }

    cfocus is set in the target frame (left) whenever you click in a frame element there. It seems that the selection isn’t created correctly - it is set for the beginning of the field regardless.

    Any ideas would be welcome.

    Very handy script and I would have liked to use this with a css fixed box in the same frame but alas IE wouldn’t have that either…

    -S

    December 16th, 2005 at 2:12 pm

  82. Alex adds this Comment:

    Reminder: Please post code enhancements and support requests in the forums if you don’t want them to be deleted. Thanks.

    December 16th, 2005 at 2:21 pm

  83. trinity adds this Comment:

    thanks a lot!!!

    January 12th, 2006 at 11:26 pm

  84. Owen adds this Comment:

    Thank you so much for the solution - the one and the only on the Internet … it really help me a lot…

    January 15th, 2006 at 7:26 pm

  85. MBT adds this Comment:

    You are my hero man. Thanks a bunch

    January 31st, 2006 at 8:32 pm

  86. Gordy adds this Comment:

    Nice, thanks for the code.

    February 25th, 2006 at 4:51 pm

  87. Ghada adds this Comment:

    I’m so greatful for this piece of code. What a great service you’ve done for the community.

    It’s amazing that you posted this back in 2003 and are still helping people today - three years later!

    Thanks!

    March 27th, 2006 at 4:39 am

  88. //beconfused » Blog Archive » fresh//comments adds this Pingback:

    […] I used what Alex King has found in phpMyAdmin’s source codes to insert the tags to the <textarea> via JavaScript. […]

    April 13th, 2006 at 12:01 pm

  89. nms adds this Comment:

    Many thanks for posting this piece of code. I found it off a Google search and it was a perfect drop-in solution to my problem. Awesome!

    June 26th, 2006 at 11:47 am

  90. Stine adds this Comment:

    Jibiii - it works :D Thanks!

    July 21st, 2006 at 6:26 am

  91. Srini adds this Comment:

    Thanks a lot!! Works perfect…but just a comment…copy pasting directly from the website resulted in the character ‘ showing up as ` due to which I was getting an ‘Invalid Character’ error. When I corrected that, it worked just fine…

    July 27th, 2006 at 6:09 pm

  92. Alex adds this Comment:

    Sounds like a good reason to download the JS Quicktags code.

    July 27th, 2006 at 6:11 pm

  93. Jacy adds this Comment:

    I have got some sort of result from this script. (Thanks Alex! (:D) )The inserted value is showing up where expected but not as expected. I ahve called the fuction in the following bit of code:

    function addPageHeading()
    {
    var newPageHeading = prompt(”Enter Page Heading”,”");
    var textNode = document.createTextNode(”" + newPageHeading + “”);
    insertAtCursor(document.FormName.addHere, textNode);
    document.getElementById(’addHere’).focus();
    }

    but I am getting “[OBJECT]” inserted instead of my desired value. Any suggestions in what the probem might be?

    Thanks and keep up the hard work and ultra cool blog!

    August 5th, 2006 at 2:31 pm

  94. James adds this Comment:

    Alex, do you know how to return the cursor to the middle of the inserted text so this can be applicable to a forum type text box?

    Thanks.

    August 15th, 2006 at 1:18 am

  95. James adds this Comment:

    Also in FF, the cursor doesn’t reappear in the text area after you’ve added text. Any idea about that?

    August 15th, 2006 at 1:20 am

  96. Alex adds this Comment:

    The JS Quicktags have code that does this.

    August 15th, 2006 at 6:29 am

  97. mike adds this Comment:

    Nice bit of coding dude.
    Is there any chance of a solution for Safari?

    August 15th, 2006 at 9:52 am

  98. alexking.org: Blog > JS QuickTags Work in Safari! adds this Pingback:

    […] I’m not exactly sure when it happened, but as of Version 2.0.4 (419.3), my JS Quicktags (example page) seem to work in Safari. Yay! […]

    August 15th, 2006 at 9:01 pm

  99. Alex King: JS QuickTags Work in Safari! at SocialCode adds this Pingback:

    […] I’m not exactly sure when it happened, but as of Version 2.0.4 (419.3), my JS Quicktags (example page) seem to work in Safari. Yay! […]

    August 24th, 2006 at 3:38 am

  100. Liam Clarke adds this Comment:

    Fantastic code, man, kudos.

    September 5th, 2006 at 5:24 am

  101. David Levin adds this Comment:

    Nicely done!!!

    September 10th, 2006 at 12:28 pm

  102. Alejandro Garza adds this Comment:

    Great! Been looking for this for a while! Greets from sunny mexico.

    September 14th, 2006 at 3:51 pm

  103. Stu adds this Comment:

    Excellent, this has been very helpful thankyou!

    October 9th, 2006 at 4:02 am

  104. eswar adds this Comment:

    I tried to get the cursor position in a text box, i got on IE but can i have code which works on MOZILLA NETSCAPE OPERA …, is there any tutorial for that…

    function GetCursorPosition() {
    var obj = document.activeElement;
    var cur = document.selection.createRange();
    var pos = 0;
    if (obj && cur) {
    var tr = obj.createTextRange();
    if (tr) {
    while (cur.compareEndPoints(”StartToStart”, tr) > 0)
    {
    tr.moveStart(”character”, 1);
    pos++;
    }
    return pos;
    }
    }
    return -1;
    }

    -eswar

    October 9th, 2006 at 10:38 am

  105. Gijs adds this Comment:

    Thanks!

    October 10th, 2006 at 5:09 am

  106. danielin_ballack adds this Comment:

    you’re great, man!!!!

    October 18th, 2006 at 12:09 am

  107. Mike adds this Comment:

    Has anyone figured out how to use this code to paste the contents of the clipboard at the position?

    October 28th, 2006 at 9:45 am

  108. Sean adds this Comment:

    great work. i have one question here. if your webpage has multiple textboxes and you need to insert a symbol into each textbox is there any way you can find the active textbox?

    insertAtCursor(document.formName.ActiveTextBox, ‘this value’);

    November 15th, 2006 at 2:10 pm

  109. sreevinod nair adds this Comment:

    Thank you! It worked perfect for me!! And This piece of code is used to insert a character
    into a particular location.

    function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
    myField.focus();
    var sel = document.selection.createRange();
    sel.moveStart(’character’,0);
    sel.select();
    sel.moveEnd(’character’,1);
    sel.text = ”;
    sel.select();
    sel.text = myValue;
    }
    }

    December 22nd, 2006 at 12:11 am

  110. masterhack adds this Comment:

    sorry about my bad english because i am from slovakia(i dont think that someone know where it is :D) but i must give my thanks to this tutorial or what it is. nice!

    December 25th, 2006 at 6:36 am

  111. arkin adds this Comment:

    The save_scrollbar & restore_scrollbar functions rule!!

    the rest too ;)

    December 28th, 2006 at 9:08 am

  112. Ilya Lebedev adds this Comment:

    Try to use DocumentSelection http://svn.debugger.[...]selection.js it offers the most comprehensive interface for text manipulations.

    Demo: http://debugger.ru/d[...]tualkeyboard

    January 23rd, 2007 at 5:55 am

  113. plmad666 adds this Comment:

    This is a great piece of code !!!

    I’ve lost several hours trying to insert text in a textarea with createRange & caretpos but it never works.

    I think that is a hosting problem. :(

    But this piece of code works great in IE, Morzilla and Opera !!! :)

    Thank you very much.

    March 5th, 2007 at 4:45 pm

  114. Eric adds this Comment:

    If you are interested in a function that determines whether the cursor is at the end of a textarea, please have a look at
    http://jdev.blogsome[...]a-enter-key/

    March 19th, 2007 at 8:52 am

  115. Cornjam Snakecharmer adds this Comment:

    For those getting frustrated with the supplied code not working, there is a simple grammatical mistake.

    Fixed Version:

    function insertAtCursor(myField, myValue) {
    //IE support
    if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
    }
    //MOZILLA/NETSCAPE support
    else if (myField.selectionStart || myField.selectionStart == ‘0′) {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);
    } else {
    myField.value += myValue;
    }
    }
    // calling the function
    insertAtCursor(document.formName.fieldName, ‘this value’);

    July 3rd, 2007 at 9:12 am

  116. checcco adds this Comment:

    in the previous post you have to change ‘0′ with ‘0′

    hpe this helps

    July 12th, 2007 at 6:53 am

  117. rudkin adds this Comment:

    Thanks - works beautifully!

    (Although watch out for the quote typo on line:
    else if (myField.selectionStart || myField.selectionStart == ‘0′) { … )

    September 27th, 2007 at 8:53 am

  118. Ken P adds this Comment:

    Thank you for the great function.

    A quick fix for scrolling issue cited above:

    // save scrollTop before insert
    var restoreTop = myField.scrollTop;
    myField.value = myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);
    if (restoreTop > 0) {
    // restore previous scrollTop
    myField.scrollTop = restoreTop;
    }

    December 21st, 2007 at 2:57 pm

  119. Alex adds this Comment:

    Please read this comment from 2004.

    December 21st, 2007 at 2:59 pm

  120. evilripper adds this Comment:

    Wow!!! Your code is great!!

    Thanks :-D

    July 16th, 2008 at 2:15 am

  121. How to insert tabs in a textarea » Forums, Blogs, Wikis adds this Pingback:

    […] The majority of the solution came from phpMyAdmin via alexking.org. […]

    July 20th, 2008 at 3:29 pm

  122. finalday adds this Comment:

    question for you..

    i need to use something like this code into an iframe with design mode on..

    passing values to this function, it works only with strings.. if i pass as myvalue ‘document.getElementsByTagName’, it doesn’t work… why???

    July 23rd, 2008 at 4:16 am

  123. david adds this Comment:

    This is great. By far the most clear and usable example I found. THANKS!! I and all the people my application will help live thank you much.

    August 28th, 2008 at 10:58 am

  124. Chippo adds this Comment:

    Does anyone know of how to do the same thing with an iframe (WYSIWYG)? As I am building one at the moment which is part of my other script, but what Im trying to do is insert an image into the iframe with an alt tag etc, any ideas?

    September 23rd, 2008 at 8:35 am

Add a Comment

Please note: Use of a non-personal web site or blog in the field below and/or comments that are off-topic, personal attacks, or support requests will likely be removed at my discretion.

Note: This post is over 5 years old. You may want to check later in this blog to see if there is new information relevant to your comment.

2 Quick Baseball Thoughts » « tasks 1.6b6 released

About This Site

This is the personal web site of Alex King, a web developer in Denver, Colorado USA. More...


Crowd Favorite

Crowd Favorite is my software and web development business.

We build web applications, design and develop custom WordPress themes and plugins, and build custom sites using WordPress as a CMS.


I also have a tumblog that aggregates my online content from other services (Twitter, Flickr, del.icio.us. etc.).

America

Ads