Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to work out where in a p's text a mouse click event occurred?

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?

like image 201
Armand Avatar asked Sep 02 '10 14:09

Armand


People also ask

What is mouse click event?

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 .

Which of the following is a mouse event?

Mouse event typesMouse button is clicked/released over an element. mouseover/mouseout. Mouse pointer comes over/out from an element. mousemove.

How many mouse events are there?

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.


2 Answers

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 :)

like image 161
David Avatar answered Sep 28 '22 06:09

David


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.

like image 36
Vlad Tsepelev Avatar answered Sep 28 '22 07:09

Vlad Tsepelev