Get the current word in paragraph on click event in jquery
Asked Answered
I

2

5

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'

Imre answered 7/9, 2012 at 15:52 Comment(2)
What tag is around the text you want to get clickable?Voyage
Would you a double click (highlighting the text) be sufficient instead?Cermet
V
17

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

Voyage answered 7/9, 2012 at 16:24 Comment(7)
yeah that works, although i get NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsISelection.collapse] [Break On This Error] range.collapse(); errorImre
When i remove the range.collapse(); it works, should I remove it?Imre
@PatREllery that's a common error in Firefox (not just with this code) I can figure out why this happens but sometimes this is fixed when you use e.g '.method(null);' or something related to fill the arguments (but does not work for this case). Well, removing it won't cause nothing important, it will just leave the text highlighted until the user clicks other part of the window and the range collapses :-) comment that line on Firefox and take a look.Voyage
@PatREllery for Firefox use this: range.collapse(range.anchorNode, range.anchorOffset); (Will solve your error)Voyage
Does this work only because double-clicking creates a selection? I don't think this can be adapted to, say, single-clicking or hovering over a word or letter, right?Fagan
@AhmedFasih Yes, you're right. However, it seems that there's a way but I don't know if that works fine in all browsers and also don't like the code at all, take a look: jsfiddle.net/M3kgp (btw, this applies when using a textarea).Voyage
Hi, Nice answer for sure. But If I want to bold only that double clicked text. how can we do this. I tried $(this).css({'font-weight':'bold'}); but It's making whole paragraph bold. find demo what I have tried jsfiddle.net/5D4d3/315Ulcerate
P
2

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

Pectoralis answered 28/12, 2017 at 17:37 Comment(1)
there's a problem : click on the blank area will also trigger the fuction !Canice

© 2022 - 2024 — McMap. All rights reserved.