Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected word when double-click on div, p, span?

Can you get the word the user has double-clicked on? I've tried in a onDblClick eventhandler but selectionStart is undefined there; and the onselect event seems to be available only for TextArea.

like image 200
Tim Avatar asked Feb 17 '10 14:02

Tim


1 Answers

You can use document.selection.createRange().text in IE, and window.getSelection().toString() in firefox and webkit, and attach to the ondblclick handler like so:

document.ondblclick = function () {
   var sel = (document.selection && document.selection.createRange().text) ||
             (window.getSelection && window.getSelection().toString());
   alert(sel);
};

References:

  • MSDN, for document.selection
  • MDN, for window.getSelection()
like image 107
David Tang Avatar answered Oct 12 '22 23:10

David Tang