10

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

2 Answers2

17

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.

Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • Beat me a few minutes. I was about to suggest the same thing. +1 – Jose Basilio May 18 '09 at 17:10
  • Sorry, the problem was that the user defined getSelection function is clobbering window.getSelection. An easy fix is just renaming the user defined function. –  May 24 '10 at 21:56
  • 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? –  May 27 '10 at 08:13
  • @misterMatt Yes, the function covers all the ways in which one would get the selected text in different browsers. – Paolo Bergantino May 27 '10 at 14:27
4

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

Emil Sierżęga
  • 1,785
  • 2
  • 31
  • 38
Praveen Angyan
  • 7,227
  • 29
  • 34