/    Sign up×
Community /Pin to ProfileBookmark

detecting text selection

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

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@ilbonparaurtiDec 30.2003 — 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.
Copy linkTweet thisAlerts:
@Mr_JDec 30.2003 — 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>
Copy linkTweet thisAlerts:
@SnowCrashJan 03.2004 — 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:

[URL=http://dev.lophty.com/ahoy/article.htm]Range object Ns6+ / Mozilla[/URL]

[URL=http://www.pbwizard.com/Articles/Moz_Range_Object_Article.htm]Mozilla range object[/URL]

[URL=http://www.webreference.com/js/column12/selectionobject.html]Selection object in IE4+ Ns4 [/URL]

[URL=http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html]W3c Specs on range object[/URL]
×

Success!

Help @pytho spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...