javascriptjqueryjquery-events

How to differentiate single click event and double click event?


I have a single button in li with id "my_id". I attached two jQuery events with this element

1.

$("#my_id").click(function() { 
    alert('single click');
});

2.

$("#my_id").dblclick(function() {
    alert('double click');
});

But every times it gives me the single click


Solution

  • You need to use a timeout to check if there is an another click after the first click.

    Here is the trick:

    // Author:  Jacek Becela
    // Source:  http://gist.github.com/399624
    // License: MIT
    
    jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
      return this.each(function(){
        var clicks = 0, self = this;
        jQuery(this).click(function(event){
          clicks++;
          if (clicks == 1) {
            setTimeout(function(){
              if(clicks == 1) {
                single_click_callback.call(self, event);
              } else {
                double_click_callback.call(self, event);
              }
              clicks = 0;
            }, timeout || 300);
          }
        });
      });
    }
    

    Usage:

    $("button").single_double_click(function () {
      alert("Try double-clicking me!")
    }, function () {
      alert("Double click detected, I'm hiding")
      $(this).hide()
    })
    
    <button>Click Me!</button>
    

    EDIT:

    As stated below, prefer using the native dblclick event: http://www.quirksmode.org/dom/events/click.html

    Or the one provided by jQuery: http://api.jquery.com/dblclick/