Preventing doubleclick firing two clicks with jQuery

A user of my wife’s workshop page reported that they couldn’t click to expand a div – when they did it opened and then immediately closed again. Experimentation showed that in fact they were double clicking rather than single clicking – registering two click events in fact. My original code was:

$('h3 span a').click(function() {
    $(this).parent().parent().siblings(".event_hidden").slideToggle();
    return false;
});

When I started thinking about it, I couldn’t immediately see how to separate the two events – after all, a doubleclick is just two clicks, isn’t it? Fortunately jQuery provides an easy solution by using the event properties:

$('h3 span a').click(function(event) {
    if(event.detail==1){//activate on first click only to avoid hiding again on double clicks
        $(this).parent().parent().siblings(".event_hidden").slideToggle();
    }
    return false;
});

Edit 14 November 2010 Actually, problem not quite solved, since I found that IE8 and under (I don’t know about IE9) don’t recognise event.detail, and hence the code above prevents the slideToggle working entirely. Fortunately, neither does the doubleclick problem seem to affect these browsers, and hence I amended my code to:

$('h3 span a').click(function(event) {
    if(!event.detail || event.detail==1){//activate on first click only to avoid hiding again on double clicks
        $(this).parent().parent().siblings(".event_hidden").slideToggle();
    }
    return false;
});

Tags:

7 responses to “Preventing doubleclick firing two clicks with jQuery”

  1. Adam says:

    This was a very helpful tip. The latest version of firefox (v4) they seem to have fixed this issue however

  2. Shiva says:

    Was ver helpfull. worked for me. thanks.

  3. Dan says:

    Excellent tip. Saved me some time, thanks.

  4. Rares says:

    Thanks !

  5. Saint says:

    Good mannn!!!! Tkss!!!

  6. Ramesh Kadirisani says:

    IE10 in Windows 8 does not reset .detail property in mouse events.
    After each mousedown .detail is increased. Even after reloading page .detail is not reset. Only right mouse button click resets the property to initial value.
    Reference: https://github.com/clientside/amplesdk/issues/187

  7. Saurabh says:

    Super helpful, thanks. Also, like to thanks Ramesh for added info. As I am using a different flow I modified your solution as below –
    if(typeof e.originalEvent.detail !== “undefined” && e.originalEvent.detail > 1){
    return
    }

Useful? Interesting? Leave me a comment

I've yet to find a way of allowing code snippets to be pasted into Wordpress comments - so if you're trying to do this you'd be better off using the contact form.