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

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) {<br />//IE support<br />if (document.selection) {<br />myField.focus();<br />sel = document.selection.createRange();<br />sel.text = myValue;<br />}<br />//MOZILLA/NETSCAPE support<br />else if (myField.selectionStart || myField.selectionStart == '0') {<br />var startPos = myField.selectionStart;<br />var endPos = myField.selectionEnd;<br />myField.value = myField.value.substring(0, startPos)<br />+ myValue<br />+ myField.value.substring(endPos,myField.value.length);<br />} else {<br />myField.value += myValue;<br />}<br />}<br />// calling the function<br />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

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注