Peter Bowyer <> wrote:

> If you test it then you'll see what's the problem - the {img} is always
> added to the end of the textarea.

Yes, there is never a caretPos property to read, so the insert-in-text
code cannot work. There is another function that usually goes with the
piece of code you quoted that reads the caret position/selection and
stores it in a 'caretPos' property of the object, which is then read
when the text is inserted. This function (storeCaret) is normally bound
to click, dblclick, keyup etc. events of the text input so that it gets
called whenever the selection changes.

This is done because clicking on a link or button defocuses the text
field, making it impossible to read the selection. I prefer to
re-focus() the element and then read its selection. This gives
the somewhat cleaner code:

  function addText(v) {
    var el= document.forms['foo'].elements['bar'];
    var text= '{img or something '+v+'}';
    if (document.selection)
      document.selection.createRange().text= text;
      el.value+= text;
    return false;

call with eg. <a href="#" onclick="return addText('qux')">. (Avoid
javascript: links.)

> Another question: anyone know of some free javascript functions/scripts
> that bring together the IE way shown above and the Mozilla/W3C DOM
> compatible methods?

Sadly I don't believe it's possible. DOM Level 2 Range does not specify
a way of getting hold of a Range object corresponding to the user's
selection. Mozilla implements this using the window.getSelection()
method, but this doesn't work for form fields (bug 85686, which is
unlikely to be fixed before 1.0). Mozilla does also implement
'selectionStart'/'selectionEnd' for input fields - but, infuriatingly,
not textareas!

...unless you want to build your own textarea-like object out of DHTML
just for Mozilla. not fun...