How can I detect if any text is highlighted using jQuery.
I tried:
$(document).mouseup(function(){
if(typeof window.getSelection!="undefined"){
console.log("text highlighted");
}
});
but it dind't work, the console.log() fired each time the mouse click was released, even if there wasn't any highlighted..
Try this:
$(document).mouseup(function(){
var highlightedText = "";
if (window.getSelection) {
highlightedText = window.getSelection().toString();
}
else if (document.selection && document.selection.type != "Control") {
highlightedText = document.selection.createRange().text;
}
if(highlightedText != "")
console.log("text highlighted.");
});
$(document).on("mouseup", function() {
if (window.getSelection().toString() != "") {
console.log("text highlighted :" + window.getSelection().toString());
}
});
This is another way this could be done
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