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