Reputation: 5493
I need to insert some text into a textarea at the place where the cursor is, how can i do this without jquery?
Upvotes: 2
Views: 786
Reputation: 38603
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>
Upvotes: 0
Reputation: 344271
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');
Upvotes: 1
Reputation: 7426
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.
Upvotes: 0