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.
Thanx for posting this, couldn’t find it anywhere else on the net.
Nice one!
Now, how do I delete at the cursor position? tricky…
You just manipulate the string using the cursor position as a base, it isn’t hard.
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.
Depends on your version of Netscape I guess. Current versions insert at the cursor – old versions and unsupported browsers insert at the end.
Thank’s man…:)
thank you very much!
I tried on Netscape 7.0, it doesn’t seem to work… ;(
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;
}
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+.
Great thanx to you! It helped me very much.
Wow great little piece of code!
Been looking for this all over
Thanks
Doesn’t work in Opera either.
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… 😉
This is code is very useful. Thankyou so much
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.
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.
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.
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
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.
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.
Yep, this was actually fixed in my Quicktags already.
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.
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;
}
}
If you do that, you can’t just keep typing or you’d overwrite the inserted text.
Anyone know how insert text before and after a highlighted/selected text?
Um, that is what this does…
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, ‘‘,’‘)”
You should look at the Quicktags code – it already had this functionality.
Thanks!, you make my work easier!
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
How is this any different than my JS Quicktags?
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.
This is why I have the note at the top of the post…
A fair point. I’d missed that bit and went straight for the code. Sorry again.
I was wondering how to get it working from a pop-up window, to a normal window with the textarea (smiley idea from tagboard).
I found out for IE:
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.
I don’t think my Quicktags display this behavior, why don’t you borrow that code?
I posted my script but it was deleted..
This isn’t a support forum. 🙂
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.
Like I told David: why don’t you use the Quicktags? They already do this…
Thank you very much. I knew it was possible, I just couldn’t find the mothods and properties anywhere else.
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
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 🙂
Nice code… THX
This code was exactly what I was looking for. Thanks!
Great bit of code. Is this also covered under the LGPL? And any specific restrictions for commercial use?
Why don’t you just use the Quicktags code as a base (which has an updated version of this code anyway).
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.
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;
}
}
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:
http://www.enetplanet.com/kb_en/
Why on screen English keyboard? Because some people can not type on hardware keyboards due to physical challenges.
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.
Thanks a lot for this most useful piece of code !
Hi, awesome script – thanks. I was playing around with the example page:
https://alexking.org/software/javascript/js_quicktags/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!
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
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.
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.
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.
IE for Mac is definitely not supported – not much a developer can do to support a browser that doesn’t work properly.
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?
Sorry, never heard of that problem nor can I reproduce it.
ah well.. just thought you should know.
Maybe you can post more information in the JS Quicktags support forum so we can look into it futher.
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 🙂
Thanks!
This is perfect 🙂
Thanks for this piece of code 🙂 Works like a charm!
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.
Brilliant. An answer to years of searching 🙂 AND it’s easily customizable!! Thanks so much!
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
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();
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…
hey!!! worked for me!!! thanks!
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…
That’s strange, I have no such problem in Firefox 1.0.7, nor has anyone else let me know they have seen this.
Hey, thanks! I could not find this anywhere else!
Thanks for figuring this out and posting to the web, I was having trouble trying to figure all this out in a portable way.
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 ]
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!
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
Reminder: Please post code enhancements and support requests in the forums if you don’t want them to be deleted. Thanks.
thanks a lot!!!
Thank you so much for the solution – the one and the only on the Internet … it really help me a lot…
You are my hero man. Thanks a bunch
Nice, thanks for the code.
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!
[…] I used what Alex King has found in phpMyAdmin’s source codes to insert the tags to the <textarea> via JavaScript. […]
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!
Jibiii – it works 😀 Thanks!
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…
Sounds like a good reason to download the JS Quicktags code.
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!
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.
Also in FF, the cursor doesn’t reappear in the text area after you’ve added text. Any idea about that?
The JS Quicktags have code that does this.
Nice bit of coding dude.
Is there any chance of a solution for Safari?
[…] 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! […]
[…] 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! […]
Fantastic code, man, kudos.
Nicely done!!!
Great! Been looking for this for a while! Greets from sunny mexico.
Excellent, this has been very helpful thankyou!
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
Thanks!
you’re great, man!!!!
Has anyone figured out how to use this code to paste the contents of the clipboard at the position?
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’);
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;
}
}
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!
The save_scrollbar & restore_scrollbar functions rule!!
the rest too 😉
Try to use DocumentSelection http://svn.debugger.[...]selection.js it offers the most comprehensive interface for text manipulations.
Demo: http://debugger.ru/d[...]tualkeyboard
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.
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/
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’);
in the previous post you have to change ‘0′ with ‘0’
hpe this helps
Thanks – works beautifully!
(Although watch out for the quote typo on line:
else if (myField.selectionStart || myField.selectionStart == ‘0′) { … )
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;
}
Please read this comment from 2004.
Wow!!! Your code is great!!
Thanks 😀
[…] The majority of the solution came from phpMyAdmin via alexking.org. […]
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???
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.
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?
Thanks for sharing this !
I like this function very much ~
your is very useful form me, can u help me how to inerst content in div element texts instead of textarea
Alex,
I’ve only been able to get this script to work if the function is called from an “input†style button element. If it’s called from say a “div” or “ul” element it does not work in IE. The cursor returns to the front of the input. I’ve tried changing every event handler sequence I can drum up but it still does not hold the cursor position. Any thoughts on why?
[…] but what about IE? The challenge was weird, but I finally got a way around, starting an idea here. What I’ve done is I used Prototype to extend the Form Element Methods and simply add a […]
[…] = sOPT End Sub Sub File_Position() ‘**** ‘* Inserting at the cursor using JavaScript ‘* https://alexking.org/blog/2003/06/02/…ing-javascript / ‘**** sTMP = document.getElementById("Entry").Value If sTMP = "" Then Exit […]
thanks a lot for that. its working fine.
it worked for me with a little changes:
function doPaste(myField)
{
if (document.selection)
{
myField.focus();
sel = document.selection.createRange();
sel.execCommand(“Paste”);
}
}
Html link: doPaste(document.b3.txt1);
thanks.ı use this function.
Works like a charm, I was looking for a small text editor, with your code I am writing my own … thanks alot
thank you guys all participated in the discussion
Thank you – am using this code snippet
It works great in safari, firefox, and chrome!!
Thanks I looked forever for this code… so many versions out there that are so complicated… good job on simplicity!
Great snippet :D!
It works beautifully :D!
Thank you very much for sharing this here.
Another handy method for Mozilla/Netscape browsers is element.setSelectionRange(pos, pos) , which sets the position of the cursor :D!
Thank you very much for this code. It works great.
[…] Fresh Comment widget in your sidebar.)Final wordsI used what Alex King has found in phpMyAdmin‘s source codes to insert the tags to the textarea via JavaScript.I […]
thanks man.
Thanks man! A thousand times thanks! Simple and efficient.