How can I get the co-ordinates of selected text in Javascript ?
As Sarfraz's links refer mainly to textboxes and I assume you want to get the position of any selection, here's the steps needed to get it:
- Get the selection
- Wrap the first letter of the selection to a span element
- Calculate the offset of the said span element. jQuery's
offset
method is useful here. - Remove the created span
That's it in a nutshell, I won't start implementing the code for that because it's tricky with IE having one kind of code and other browsers other kind.
Note that this method works reliably only on text selections, if you have a selection starting with an image for example, things might get difficult.
Isn't OnMouseDown() and OnMouseUp() events are helpful??
To select the text you need to click mouse button down .. and to complete the selection you do mouseUp ..
with OnMouseDown event you can get the Co-ordinates of Initial letter and with OnMouseUp the last letter ..
Check this code out .. : ..
<head>
<script type="text/javascript">
function show_coords(event)
{
x=event.clientX;
y=event.clientY;
document.getElementById("one").innerHTML='X coords: ' + x + ', Y coords: ' + y;
}
function show_coords2(event)
{
x=event.clientX;
y=event.clientY;
var newb= document.getElementById("one").innerHTML+'<br/>'+'X coords: ' + x + ', Y coords: ' + y;
document.getElementById("one").innerHTML=newb;
}
</script>
</head>
<body onMouseDown="show_coords(event)" onMouseUp="show_coords2(event)">
<p>Click in the document to see the co-ordinates of the selected text</p>
<p id="one"></p>
</body>
Outputs something like this::
Click in the document. An alert box will alert the x and y coordinates of the mouse pointer.
X coords: 8, Y coords: 15
X coords: 555, Y coords: 17
There is no problem with mouseDown .. but On mouseUp both the co-ordinates depend on the exact position of the cursor where you trigger the event .. that is why you can see minor change in co-ord Y in above example ..
Please give a feedback writing as comments ..
Hope it helps :-)
Check this link : http://javascript.internet.com/page-details/highlighted-text.html
I don't have knowledge on jQuery. So I support only Infant Programmer's suggestion.
I tried onMouseOver() event .. works effectively (in my view) .. I have just modified "Infant Programmer's" code .. Here it is :
<head>
<script type="text/javascript">
function show_coords(event)
{
x=event.clientX;
y=event.clientY;
document.getElementById("one").innerHTML='X coords: ' + x + ', Y coords: ' + y;
}
</script>
</head>
<body>
<p onMouseOver= "show_coords(event)">Hover on this line to see the co-ordinates of the selected text</p>
<p id="one"></p>
</body>
I tried even OnSelect() event .. that seems not work.