I have a <p>
containing text. When the <p>
is clicked on, I create a <textarea>
containing the text from the <p>
. Is it possible to calculate where in the <p>
's text the click occurred, and move the <textarea>
's cursor to that same point?
The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click , dblclick , mouseup , mousedown . MouseEvent derives from UIEvent , which in turn derives from Event .
Mouse event typesMouse button is clicked/released over an element. mouseover/mouseout. Mouse pointer comes over/out from an element. mousemove.
When you click an element, there are no less than three mouse events fire in the following sequence: The mousedown fires when you depress the mouse button on the element. The mouseup fires when you release the mouse button on the element. The click fires when one mousedown and one mouseup detected on the element.
I don't believe so, no. The DOM just knows what containing element received the click event, it doesn't distinguish between pieces of text within the containing element unless they are elements themselves. And I doubt you want to wrap every character in your text with its own element tag :)
Hope this simple example helps:
<html>
<head/>
<body>
<script type='text/javascript'>
function getPosition()
{
var currentRange=window.getSelection().getRangeAt(0);
return currentRange.endOffset;
}
function setPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
function test()
{
setPosition('testId', getPosition());
}
</script>
<p onclick = 'test()'>1234567890</p>
<textarea id='testId'>123467890</textarea>
</body>
</html>
Or you can use third-party JS library like jQuery - see this example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With