abhishektiwari abhishektiwari - 1 year ago 59
Javascript Question

Selected text event trigger in Javascript

It may sound a newbie question but I wanted to know how I can trigger a custom JavaScript function when someone selects a given text fragment on a page using mouse. Also is there any way to find the position of selected text on the webpage?

To be more clear, text fragment can be part of a sentence or a word or a phrase or whole a paragraph.

Answer Source

There is no "Text was selected" (DOM) event, but you can bind a mouseup event to the document.body. Within that event handler, you might just check the




methods. There are several topics on Stackoverflow, like this one http://stackoverflow.com/questions/845390/javascript-to-get-paragraph-of-selected-text-in-web-page.

I'm not sure what you mean with "finding the position", but to stay in my example world you could use the event propertys for X+Y mouse positions.

Example: http://www.jsfiddle.net/2C6fB/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download