JSFiddle - React, Tailwind, and code Playground
HTML
<div>
Some text text text
</div>
<div class="target">
Target box with text
</div>
CSS
div{
display: inline-block;
margin: 20px;
border: 1px solid;
padding: 10px;
}
JavaScript
var inArticle = false;
// The class you want to check:
var parentClass = "target";
function checkParent(e){
if(e.parentElement && e.parentElement != $('body')){
if ($(e).hasClass(parentClass)) {
inArticle = true;
return true;
}else{
checkParent(e.parentElement);
}
}else{
return false;
}
}
$(document).on('mouseup', function(){
// Check if there is a selection
if(window.getSelection().type != "None"){
// Check if the selection is collapsed
if (!window.getSelection().getRangeAt(0).collapsed) {
inArticle = false;
// Check if selection has parent
if (window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement) {
// Pass the parent for checking
checkParent(window.getSelection().getRangeAt(0).commonAncestorContainer.parentElement);
};
if (inArticle === true) {
// If in element do something
alert("You have selected something in the target element");
}
};
}
});