Selected text event trigger in Javascript
How to trigger a 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 page?
Update: To be more clear, text fragment can be part of a sentence or a word or a phrase or whole a paragraph.
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
document.selection.createRange().text
or
window.getSelection()
methods. There are several topics on Stackoverflow, like this one 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/
Here's a quick mashup:
$('div').mouseup(function() {
var text=getSelectedText();
if (text!='') alert(text);
});
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
<div>Here is some text</div>
Demo: http://jsfiddle.net/FvnPS/11/