37

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.

7
  • 1
    That's because a click is a mousedown followed by a mouseup.
    – gen_Eric
    Apr 30, 2012 at 20:19
  • 3
    mousedown + mouseup = click. Highlighting does it, so it is triggering click. Apr 30, 2012 at 20:19
  • What is your question? Do you want to stop the click happening? Only allow click if no text selected? Apr 30, 2012 at 20:22
  • Not in my case (Opera). And btw, shouldn't mousedown + mouseup = click hold only if there is a small (system-definable) time delay between the events?
    – Imp
    Apr 30, 2012 at 20:22
  • So is there any kind of work around?
    – krische
    Apr 30, 2012 at 20:23

3 Answers 3

83

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/

3
  • 2
    probably want to check the length haveSel = getSelection().toString().length > 0
    – Brad Kent
    Apr 23, 2015 at 15:55
  • 7
    To not break the whole app when a user has text selected somewhere else it might be good to check that the selected text is in the relevant element: if(!e.target.contains(getSelection().anchorNode)). Mar 22, 2016 at 16:20
  • 3
    Checking for selection elsewhere does not seem to be necessary. The reason is that a "true" click with clear any selection elsewhere on the page.
    – Necreaux
    Nov 2, 2018 at 17:19
8

As I posted on comment, mosuedown + mouseup = click which is exactly what highlighting does. There is workaround for this.. see below,

var isClick = 0;
$('#click').click(function() {
    if (isClick == 1) {
        alert("clicked");
    }
}).mousedown(function () {
    isClick = 1;
}).mousemove(function () {
    isClick = 0;
});

DEMO

1
  • 5
    Checking if the mouse moved between mousedown and mouseup, clever :-P
    – gen_Eric
    Apr 30, 2012 at 20:25
2

jsFiddle: http://jsfiddle.net/ym5JX/8/

$('#click').click( function()
{
    if ( getSelection() == "" )
    {
        alert("clicked");
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.