0

I have the following JS that inserts some content into a textarea at the end of whatever is in the textarea currently. This all works fine with the following code:

<script>
if (opener.document.post.sMessage.createTextRange && opener.document.post.sMessage.caretPos) {
  var caretPos = opener.document.post.sMessage.caretPos;
  caretPos.text = '\n\n![](http://example.com/image.png)';
} else {
opener.document.post.sMessage.value += '\n\n![](http://example.com/image.png)';
}
self.close(); //close popup
</script>

How can this be modified to insert the content into the textarea where the cursor was in the textarea (instead of just at the end of the existing text)?

GWR
  • 1,878
  • 4
  • 26
  • 44
  • Possible duplicate : [Insert text into textarea at cursor position (Javascript)](http://stackoverflow.com/questions/11076975/insert-text-into-textarea-at-cursor-position-javascript) – Shady Alset May 17 '16 at 15:19
  • I've been through those. I guess my problem here is different because the js needs to refer back to the parent window from a pop-up – GWR May 17 '16 at 19:27

2 Answers2

1

Don't have enough reputation to comment, but @GMKHussain's answer contains a typo, I believe.

I think in the line + elem.value.substring(endPos, elem.value.length); endPos should be replaced with _endSelection: + elem.value.substring(_endSelection, elem.value.length);

0

Solution with VanillaJS

function addContentAtCursorFunc( elem, newContent ) {
    
    if (elem.selectionStart || elem.selectionStart == '0') {
        let _startSelection = elem.selectionStart;
        let _endSelection = elem.selectionEnd;
            elem.value = elem.value.substring(0, _startSelection)
            + newContent
            + elem.value.substring(endPos, elem.value.length);
    } else {
        elem.value += newContent;
    }
}


const button = document.getElementById('myBtn');
const textarea = document.getElementById('myTextarea');


button.addEventListener('click', event => {
  addContentAtCursorFunc( textarea , "  *| I'M NEW CONTENT! |*  ")
  return false
});
<textarea id="myTextarea" cols="40" rows="3">Select some of this text and then hit the button.</textarea>

<button id="myBtn">Type some stuff</button>
GMKHussain
  • 3,342
  • 1
  • 21
  • 19