Javascript – Prevent click event from firing when dblclick event fires

dom-eventsjavascript

I'm handling both the click and dblclick event on a DOM element. Each one carries out a different command, but I find that when double clicking on the element, in addition to firing the double click event, the click event is also fired twice. What is the best approach for preventing this behavior?

Best Answer

In case anyone else stumbles on this (as I did) looking for an answer, the absolute best solution that I could come up with is the following:

    $node.on('click',function(e){
      if(e.originalEvent.detail > 1){
         return;
        /* if you are returning a value from this
         function then return false or cancel 
         the event some other way */
      }
    });

Done. If there is more than one click back to back, the second, third,etc. will not fire. I definitely prefer this to using any sort of timers.

I got myself pointed in this direction by reading this.


Incidentally: I was first researching this problem because I accidentally double clicked a paginated link, and the event fired and finished twice before the callback could happen.

Before coming up with the code above, I had

 if e.originalEvent.detail === 2 //return

however, I was able to click on the link 3 times (a triple click), and though the second click didn't fire, the third did