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

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.


Here you go, a blog article that describes how you do this using jQuery. His test implementation is similar to what you want. Namely double clicking a word pulls up the definition from a dictionary:

Using jQuery and Double clicks to get data