Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if text is highlighted on mouse up jQuery

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..

like image 389
Peter Zelak Avatar asked Dec 12 '25 03:12

Peter Zelak


2 Answers

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.");
});
like image 63
Bikee Avatar answered Dec 13 '25 15:12

Bikee


$(document).on("mouseup", function() {
    if (window.getSelection().toString() != "") {
        console.log("text highlighted :" + window.getSelection().toString());
    }
});

This is another way this could be done

like image 22
leenbean16 Avatar answered Dec 13 '25 17:12

leenbean16