Detect Which Word Has Been Clicked on Within a Text

Detect which word has been clicked on within a text

Here's a solution that will work without adding tons of spans to the document (works on Webkit and Mozilla and IE9+):

https://jsfiddle.net/Vap7C/15/

    $(".clickable").click(function(e){
s = window.getSelection();
var range = s.getRangeAt(0);
var node = s.anchorNode;

// Find starting point
while(range.toString().indexOf(' ') != 0) {
range.setStart(node,(range.startOffset -1));
}
range.setStart(node, range.startOffset +1);

// Find ending point
do{
range.setEnd(node,range.endOffset + 1);

}while(range.toString().indexOf(' ') == -1 && range.toString().trim() != '');

// Alert result
var str = range.toString().trim();
alert(str);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="clickable">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc. Proin sit amet sem purus. Aliquam malesuada egestas metus, vel ornare purus sollicitudin at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer porta turpis ut mi pharetra rhoncus. Ut accumsan, leo quis hendrerit luctus, purus nunc suscipit libero, sit amet lacinia turpis neque gravida sapien. Nulla facilisis neque sit amet lacus ornare consectetur non ac massa. In purus quam, imperdiet eget tempor eu, consectetur eget turpis. Curabitur mauris neque, venenatis a sollicitudin consectetur, hendrerit in arcu.
</p>

Detect which word has been right-clicked on within a text

After some search and test, this it seems to work on EDGE.

JSFiddle demo.

This is the main change:

$(".text123").on('contextmenu', function(evt){
evt.preventDefault(); // with this the context menu will not open
var e = window.event;
if (e.button == 2) {
/* START - And this make the selection before emulate the left click */
var range = document.caretRangeFromPoint(e.pageX, e.pageY);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
/* END */
jQuery(document.elementFromPoint(e.pageX, e.pageY)).click();
}
});

UPDATE

This update is for answer at the scroll page problem and the first and last word selection error.

The new JSFiddle.

$('.text123').click(function(e) {
s = window.getSelection();
var range = s.getRangeAt(0);
var node = s.anchorNode;

// ### && range.startOffset != 0 <--- This check very first char
while (range.toString().indexOf(' ') != 0 && range.startOffset != 0) {
range.setStart(node, (range.startOffset - 1));
}
range.setStart(node, range.startOffset + 1);


do {
range.setEnd(node, range.endOffset + 1);
} while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '' && range.endOffset < range.endContainer.length);
// ### && range.endOffset < range.endContainer.length <--- This check the last char

var str = range.toString().trim();

alert(str);
});


$(".text123").on('contextmenu', function(evt) {
evt.preventDefault();
var e = window.event;
if (e.button == 2) {
// ### - $(document).scrollTop() <--- This will fix the page scroll
var range = document.caretRangeFromPoint(e.pageX, e.pageY - $(document).scrollTop());
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
// ### - $(document).scrollTop() <--- This will fix the page scroll
jQuery(document.elementFromPoint(e.pageX, e.pageY - $(document).scrollTop())).click();
}
});

get word click in paragraphs

var p = $('p');

p
.html(function(index, oldHtml) {
return oldHtml.replace(/\b(\w+?)\b/g, '<span class="word">$1</span>')
})
.click(function(event) { alert(event.target.innerHTML) });

I took Pablo Fernandez's suggestions into account.

See it on jsFiddle.

Update

So, will this be performant (e.g., it won't freeze up a slow user's browser?) Also, could you elaborate about how event.target works?

It may very well slow the performance of a page with 30,000 words. I'd argue that is excessive and probably would benefit from being paginated, but I don't know your exact circumstances.

event.target property holds the element that started the event - the event bubbles up / propagates to its parent, which then handles the event, so you don't have 30,000 events on separate span elements.

Angular get clicked word in a text

You can achieve it by getting the selected word from text and replacing it with HTML tag to highlight it.

Here is the working example -

export class AppComponent {
text = "Start editing to see some magic happen";
selectedWord: string;

highlight(event) {
this.selectedWord = window.getSelection().toString();
this.text = this.text.replace(
this.selectedWord,
"<mark>" + this.selectedWord + "</mark>"
);
}
}

In the html file, you need to use innerHTML for text and call highlight() method on doubleclick event like this -

<p [innerHTML]="text" (dblclick)="highlight($event)"></p>

Here is also a stackbiltz working example.

Get the current word in paragraph on click event in jquery

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

Get value of the word when the word is clicked

I am not sure if I understand you correctly... As you already listen to the click-event for each a.clickable-element, I assume that your problem is the retrieval-part to get the word?

In the event-hander, the current element is added to the event-object as target. To retrieve the html/text contents one could use this element in conjunction with the textContent/innerText/innerHTML property:

viewAnnotation(e) {
const word = e.target.textContent.trim()

// Do something with `word`
}

Determining which word is clicked in an android textview

If you're targeting API level 14+, you could use getOffsetForPosition().

For previous Android version, see if you can copy the code for this method from Android source and extend your own TextView.



Related Topics



Leave a reply



Submit