User is on a webpage , uses his mouse to select stuff, how can i use javascript to know what has been selected?
Asked
Active
Viewed 8,003 times
2
-
3Do you want the nodes, or just the text? – outis Nov 09 '09 at 04:10
-
If you wanted the nodes: http://stackoverflow.com/questions/4220478/get-all-dom-block-elements-for-selected-texts – Ebrahim Byagowi Jul 21 '12 at 21:43
2 Answers
3
To get the raw text currently highlighted on the page you can do something like this:
function getSelectedText() {
return window.getSelection ? window.getSelection()
: document.selection.createRange().text;
}
Check an example of the above code here.
More info:

Christian C. Salvadó
- 807,428
- 183
- 922
- 838
1
If you're talking about the user dragging his mouse over text so that it's highlighted, use the Selection and Range objects (for Mozilla) and Selection and TextRange objects (for IE).

Tola Odejayi
- 3,019
- 9
- 31
- 46