Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript selectionchange event for a particular element only

I want to implement a JavaScrit selectionchange event on a particular div element, so if the user selects text from the DOM I want to show a highlighter box. I have implemented this for web with an onmouseup event. But I am stuck trying to implement this for mobile devices.

For mobile browsers I am binding document.selectionchange event on the DOM, but I want this to only apply for a particular element which has the content-editable class. So the highlighter will show only when the user selected text within the container on page which has the content-editable class.

document.addEventListener("selectionchange", function(evt) { 
  // Now this functionality only apply for content-editable class div.
});

How can I implement this functionality? Perhaps it could be implemented with a recursive function to find parentElement's class of anchorNode of selected text like:

var selection = ctrl.window.getSelection();

What is the best way to do this?

like image 868
Gitesh Purbia Avatar asked Sep 08 '17 05:09

Gitesh Purbia


1 Answers

Listen for the selectstart event of your target element instead. Only get the selection when this event is fired.

const targetDiv = document.getElementById("interestingDiv");
function logSelection() {  
  console.log(document.getSelection().toString());
}
targetDiv.addEventListener("selectstart", () => {
  console.log("Selection started in targetDiv");
  document.addEventListener("selectionchange", logSelection);
});

The selectstart event fires as soon as a new selection is made, so you will need some way to get the selection once it's complete. We can listen to selectionchange, with some way to stop listening after the selection is made. One option is to stop listening on mouseleave:

targetDiv.addEventListener("mouseleave", () => {
 document.removeEventListener("selectionchange", logSelection);
})
like image 175
AliOli Avatar answered Nov 14 '22 09:11

AliOli