Click to See Complete Forum and Search --> : detecting text selection


pytho
12-24-2003, 03:08 PM
Hello

I am wondering how to detect text selection by the mouse.
Assuming that I have an HTML page with text displayed in it.
Now I want to know when a user highlights a text in the page.
I want to know exactly where in the HTML code the highlighting began and where it ends.

is that possible?
can anybosy give me some tips on how to do it?

thanks in advane

Dudsmack
12-29-2003, 11:40 PM
Only I could think of doing it is determining text positions using screen position information, font size info, etc, then tracking the mouse (movement and clicks). This would involve MASSIVE amounts of CSS and JavaScript, not to mention this would be insanely difficult.

Mr J
12-30-2003, 09:28 AM
Here's a little snippet of code I came across a while back, it might give you some idea

It does not work in Moz though only IE

Just highlight some text

<script>

var colour_me;
function colorIt() {
mouseX=event.clientX
mouseY=event.clientY
colour_me=document.body.createTextRange();
colour_me.moveToPoint(mouseX, mouseY);
colour_me.expand("word");
colour_me.execCommand("ForeColor",false,"red");
alert(colour_me.text)
}
document.onclick=colorIt;


</script>

<P>Dummy Text Dummy Text Dummy Text Dummy Text
<P>Dummy Text Dummy Text Dummy Text Dummy Text
</BODY>

SnowCrash
01-03-2004, 04:43 AM
Hi
You can solve your problem with the use of the selection object (proprietary to IE and NS) in combination with the range object (w3c or proprietary IE). But it's quite difficult, especially if you want to use a standard way to solve it, because it demands for good knowledge of the DOM and it's methods.

Here some pages with help to start with:

Range object Ns6+ / Mozilla (http://dev.lophty.com/ahoy/article.htm)
Mozilla range object (http://www.pbwizard.com/Articles/Moz_Range_Object_Article.htm)
Selection object in IE4+ Ns4 (http://www.webreference.com/js/column12/selectionobject.html)
W3c Specs on range object (http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html)