Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current word in paragraph on click event in jquery

Tags:

jquery

word

I am trying to build a tool that allow people to get word or a phrase (on select), the select part is done but not the word part.

I need to be able to get the current word when someone click on a word, and i found this solution

get word click in paragraphs

unfortunately, this code change all the words and add a <span> for every words, which causes an issue on my side since i cannot add html tags in the text (css file can be imported or added dynamically)

is there's a better way to accomplish this, if possible?

EX:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec auctor ante sit amet nisl consequat volutpat.

if i click on "sit", then i will alert 'sit'

like image 399
Pat R Ellery Avatar asked Sep 07 '12 15:09

Pat R Ellery


2 Answers

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 :-)

like image 122
Oscar Jara Avatar answered Nov 10 '22 09:11

Oscar Jara


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

like image 36
CODE-REaD Avatar answered Nov 10 '22 08:11

CODE-REaD