Is there a generic way in jQuery or JavaScript (most cross-browser compatible) to check if text has been highlighted?
I am working with an HTML
Based on the above answer, here's the vanilla version.
document.addEventListener('click', function(){
if (window.getSelection().anchorNode.parentElement.classList.contains('word')) {
console.log('highlight');
}
});
I would change 'document' to the wrapping container and 'word' to whatever class/ID is on the text you want to detect a highlight on.
You can use the Selection
object :
var selection = window.getSelection();
See the documentation here : https://developer.mozilla.org/en-US/docs/Web/API/Selection
With this object, you can check the selected dom node (anchorNode
). For example :
if ($(window.getSelection().anchorNode).attr('id') === 'something') { ... }