Search code examples
javascriptcursorcursor-position

Javascript - insert image tag at the position of the cursor in the textarea


I know there are a few posts with the similar title, but they don't seem to refer to the same question. I'm trying to put the image tag at the position of the cursor inside of the specific textarea from withing the popup instantiated by the button from the same page as the textearea.

At the moment I simply append the image tag to the end of the content in textarea like so:

window.opener.document.getElementById('textarea_id').value += '<img .... />';

I've found one post here: How To insert an image at cursor position in tinymce, but obviously this one refers to the tinymce, which has some built in functions available.

Any thoughts?


Solution

  • You could use selectionStart read more about it at: https://developer.mozilla.org/en-US/docs/DOM/HTMLTextAreaElement

    window.opener.document.getElementById('textarea_id').selectionStart
    

    Also see Caret position in textarea, in characters from the start