Get the current word in paragraph on click event in jquery

爷,独闯天下 提交于 2019-11-29 04:55:31
Oscar

Well, for your solution you will need to work with selections and doubleclick event as a tricky thing and get the selected word in the generated range by the doubleclick event.

There is no other way if you don't want to introduce new tags.


Try this:

Live Demo: http://jsfiddle.net/oscarj24/5D4d3/

$(document).ready(function() {

    /* set hand cursor to let know the user that this area is clickable */
    var p = $('p');
    p.css({ cursor: 'pointer' });

    /* doubleclick event working with ranges */
    p.dblclick(function(e) {
        var selection = window.getSelection() || document.getSelection() || document.selection.createRange();
        var word = $.trim(selection.toString());
        if(word != '') {
            alert(word);
        }
        /* use this if firefox: selection.collapse(selection.anchorNode, selection.anchorOffset); */
        selection.collapse();
        e.stopPropagation();
    });

});​

Hope this helps :-)

Oscar Jara's answer (above) says, There is no other way [to return the clicked on word] if you don't want to introduce new tags. That probably was true in 2012 but currently we have getSelection:

The getSelection() property of the DocumentOrShadowRoot interface returns a Selection object, representing the range of text selected by the user, or the current position of the caret.

I have this working under Windows Chrome 63.0.3239.84 and Windows Firefox 56.0. To test it with other browers please use this jsfiddle example to test

    window.getSelection();

Related SO questions covering getSelection:

Get a word by single click

Detect which word has been clicked on within a text

Return Sentence That A Clicked Word Appears In

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