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

余生颓废 提交于 2019-12-02 22:19:49

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.

Praveen Angyan

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!