Get current word in paragraph on click event in jquery

I am trying to create a tool that allows people to get a word or phrase (optional), part of the selection is done, but not part of the word.

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

get the word in points .

Unfortunately, this code changes all words and adds a <span> for all words, which causes a problem on my side, since I cannot add html tags to the text (the css file can be imported or added dynamically)

Is there a better way to accomplish this, if possible?

Example:

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

if I click sit, then I will warn sit

+4
source share
2 answers

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

There is no other way if you do not want to introduce new tags.


Try the following:

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

+14
source

Oscar Haraโ€™s response (see above) says: โ€œThere is no other way [to return a click on a word] if you do not want to introduce new tags. It was probably in 2012, but currently we getSelection :

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

This works for me under Windows Chrome 63.0.3239.84 and Windows Firefox 56.0. To test it with other browsers, use jsfiddle example to test

  window.getSelection(); 

Related SO questions covering getSelection:

Get the word with one click

Determine which word was clicked in the text

Returning the sentence that appears with pressed Word

0
source

Source: https://habr.com/ru/post/1432979/


All Articles