I have a function (still in development) that needs to capture user selected text in a div (not text areas and input boxes so .select won’t work.). Using .click and selection and range objects works great when the selection is contained within a single element in that div but fails to trigger if the user selection spans multiple elements within the div (like multiple p’s).
$('.relevantDivClass').click(function(){
console.log('Got here');
SelObj = window.getSelection();
Range = SelObj.getRangeAt(0);
if (SelObj.anchorNode == SelObj.focusNode){
console.log('executing same node branch');
string = SelObj.toString();
console.log(string)
}
else{
console.log('executing multiple node branch');
//code...
}
});
Any ideas on how to get that event to trigger in that situation? It’s still within the relevantDivClass so I’m confused as to why the .click won’t trigger.
Use
.mouseup()instead of.click(). When highlighting text across multiple paragraphs, the ‘mouseup’ event is not triggered on the same element that ‘mousedown’ was triggered on — which is the definition of the ‘click’ event..click()works for single paragraphs because you trigger both ‘mousedown’ and ‘mouseup’ on the<p>element, and it bubbles up to its parent, the<div>.Working Demo