2

I need to insert some text into a textarea at the place where the cursor is, how can i do this without jquery?

John Stimac
  • 5,335
  • 8
  • 40
  • 60

3 Answers3

1

You may want to check the small code sample at:

Code from the above article:

function insertAtCursor(myField, myValue) {

  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;

    myField.value = myField.value.substring(0, startPos)
                  + myValue
                  + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}

// calling the function
insertAtCursor(document.getElementById('textarea_id'), 'sometext');
Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
0

Use an HTML title attribute? That will place tooltip text next to the cursor when it's over a particular element.

Or you could create a <div> with position: fixed, then position it at event.screenX, event.screenY:

<div id="tip" style="position: fixed; visibility: hidden;"></div>
<textarea onmousemove="position();" onmouseout="hide();"></texarea>
<script type="text/javascript">
  function position() {
    var d = document.getElementById('tip');
    d.style.visibility = 'visible';
    d.style.left = event.screenX + 'px';
    d.style.top = event.screenX + 'py';
  }
  function hide() {
    document.getElementById('tip').style.visibility = 'hidden';
  }
</script>
Max Shawabkeh
  • 37,799
  • 10
  • 82
  • 91
0

Please see this person's code here. This code uses the selection property of the document object to get the cursor position, and then builds a new string and stuffs it into the textarea. It also has a specialized routine for IE which has much more cumbersome logic for finding the cursor position.

G-Wiz
  • 7,370
  • 1
  • 36
  • 47