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

Answers 1

  • 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.");
    });
    

Related Articles