views:

292

answers:

2

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?

+7  A: 

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

function getSelection() {
    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 = getSelection();
    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.

Paolo Bergantino
Beat me a few minutes. I was about to suggest the same thing. +1
Jose Basilio
I can't seem to get this to work. http://erxz.com/pb/25570
misterMatt
Sorry, the problem was that the user defined getSelection function is clobbering window.getSelection. An easy fix is just renaming the user defined function.
misterMatt
@PaoloBergantino Could you explain the need for the two else if conditions? I'm guessing this sort of thing is handled differently by different browsers, is that the case?
misterMatt
@misterMatt Yes, the function covers all the ways in which one would get the selected text in different browsers.
Paolo Bergantino
+4  A: 

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

Praveen Angyan