Search code examples
javascriptevent-handlingdom-eventsdhtml

How to make a click or double click on a word on a web page to trigger an event handler?


For a page like

http://www.answers.com

if the user double clicks on any word in the page, a pop up box will show up and shows the definition for that word.

I can think of a way to use DOM scripting to break up all words in the page and then make each of them go under a separate "span" element... but otherwise isn't it true that if all the text is under a "p" element, then the "p" element node get triggered to handle the double click event, but there is no easy way of telling which word is clicked on?


Solution

  • You simply add a double click event to the entire document, like so:

    function get_selection() {
        var txt = '';
        if (window.getSelection) {
            txt = window.getSelection();
        } else if (document.getSelection) {
            txt = document.getSelection();
        } else if (document.selection) {
            txt = document.selection.createRange().text;
        }
        return txt;
    }
    
    $(document).dblclick(function(e) {
        var t = get_selection();
        alert(t);
    });
    

    If you only wanted this to work on select paragraphs, you would change the selector to p.myclass or something like that. This hinges on the fact double clicking a word highlights it in browsers. Not really sure if it's exactly how answers.com does it, to be honest.