1

I'm trying to insert the image url where the point of the is to be when editing the textarea value.

function addImageURL()
{
 var imageurl = prompt("Enter image URL", "Your name")
 var post = document.getElementById("message-put").value;

 document.getElementById('message-put').value = post + '[img]' + imageurl + '[/img]';
}

This code grabs the value inside the adds the image url next to it which I don't want, I need it to insert it where the point was when editing the textarea

Thanks

EDIT:

Like Stackoverflow, you see the image icon, you click it or click on the hyperlink, a box comes up and inserts it where you were editing the textarea :P

alt text

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
MacMac
  • 34,294
  • 55
  • 151
  • 222

3 Answers3

1

If you want to insert something at the cursor, here is something I found using teh Googlez:

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 back = (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;
}

The source: http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/ (I haven't tested this; it's from 2008 so it may be a little dated).

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
0

I think you may find what you're looking for here:

Caret position in textarea, in characters from the start

And an example implementation here:

http://javascript.nwbox.com/cursor_position/

Community
  • 1
  • 1
marapet
  • 54,856
  • 12
  • 170
  • 184
0

A technique I used when trying to achieve similar functionality in a WYSIWYG:

Retrieve parent node from selection (range) in Gecko and Webkit » StackOverflow

Might be useful if working with frames, or want to avoid some cursor issues I ran into.

Community
  • 1
  • 1
Jason
  • 2,691
  • 27
  • 28