jQuery .click() is triggering when selecting/highlighting text

krische picture krische · Apr 30, 2012 · Viewed 11k times · Source

I have a <div> with a bunch of text in it. This <div> also has a .click() event on it using jQuery.

The problem I'm having is that the .click() is being triggered when selecting/highlighting text. Even holding the mouse down for several seconds before releasing.

Here is a JSFiddle that shows the issue: http://jsfiddle.net/ym5JX/

The behavior that I would expect is that highlighting text isn't the same as clicking on the element.

Answer

Rocket Hazmat picture Rocket Hazmat · Apr 30, 2012

That's because a click is a mousedown followed by a mouseup. My suggestion is to check getSelection inside the click handler. If it's set, then you selected something, else you just clicked.

$('#click').click(function() {
    var sel = getSelection().toString();
    if(!sel){
        alert("clicked");
    }
});​

DEMO: http://jsfiddle.net/ym5JX/3/