views:

157

answers:

3

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

+1  A: 

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
i want to insert text into the middle, not replace the thing
Jcubed
Sorry, thought you meant the mouse cursor!... Let me modify my post...
Daniel Vassallo
Modified. Tested the above in Firefox.
Daniel Vassallo
Nice find. +1 for including both the source of your info in addition to the actual code.
Matt
A: 

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
no... i want to insert text into a textarea... not a tooltip
Jcubed
A: 

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.

gWiz