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.
            Asked
            
        
        
            Active
            
        
            Viewed 4,518 times
        
    7
            
            
        - 
                    1The only way I've been able to do this is to wrap each and every word in its own SPAN. Yahoo knows what word is highlighted when you right-click. And in IE, the accelerators know the highlighted word too. Are these connecting to the browser "below" the javascript/DOM layer, to some API? – Tim Feb 17 '10 at 22:36
- 
                    That is, Yahoo Search on the context-menu in Firefox. – Tim Feb 17 '10 at 22:37
2 Answers
10
            
            
        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:
 
    
    
        David Tang
        
- 92,262
- 30
- 167
- 149
0
            
            
        and window.getSelection().toString() is what I used.
I want to share that you can use baseOffset and extentOffset too.
<p>test data.</p>
<script>
  document.addEventListener("dblclick", (e)=>{
    const selection = document.getSelection()
    // console.log(selection.anchorNode.data) // is whole text: "test data."
    const selectContent = selection.anchorNode.data.slice(selection.baseOffset, selection.extentOffset)
    console.log(selectContent)    
  })
</script> 
    
    
        Carson
        
- 6,105
- 2
- 37
- 45
 
    