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?
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With