Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery bind double click and single click separately

Is there something in jquery that would allow me to differentiate between behavior on double click and single click?

When I bind both to same element only the single click gets executed.

Is there a way that wait for some time before execution of the single click to see if the user clicks again or not?

Thanks :)

like image 214
kritya Avatar asked Jun 13 '11 12:06

kritya


2 Answers

I found that John Strickler's answer did not quite do what I was expecting. Once the alert is triggered by a second click within the two-second window, every subsequent click triggers another alert until you wait two seconds before clicking again. So with John's code, a triple click acts as two double clicks where I would expect it to act like a double click followed by a single click.

I have reworked his solution to function in this way and to flow in a way my mind can better comprehend. I dropped the delay down from 2000 to 700 to better simulate what I would feel to be a normal sensitivity. Here's the fiddle: http://jsfiddle.net/KpCwN/4/.

Thanks for the foundation, John. I hope this alternate version is useful to others.

var DELAY = 700, clicks = 0, timer = null;  $(function(){      $("a").on("click", function(e){          clicks++;  //count clicks          if(clicks === 1) {              timer = setTimeout(function() {                  alert("Single Click");  //perform single-click action                     clicks = 0;             //after action performed, reset counter              }, DELAY);          } else {              clearTimeout(timer);    //prevent single-click action             alert("Double Click");  //perform double-click action             clicks = 0;             //after action performed, reset counter         }      })     .on("dblclick", function(e){         e.preventDefault();  //cancel system double-click event     });  }); 
like image 77
Garland Pope Avatar answered Sep 22 '22 19:09

Garland Pope


The solution given from "Nott Responding" seems to fire both events, click and dblclick when doubleclicked. However I think it points in the right direction.

I did a small change, this is the result :

$("#clickMe").click(function (e) {     var $this = $(this);     if ($this.hasClass('clicked')){         $this.removeClass('clicked');          alert("Double click");         //here is your code for double click     }else{         $this.addClass('clicked');         setTimeout(function() {              if ($this.hasClass('clicked')){                 $this.removeClass('clicked');                  alert("Just one click!");                 //your code for single click                           }         }, 500);               } }); 

Try it

http://jsfiddle.net/calterras/xmmo3esg/

like image 23
calterras Avatar answered Sep 19 '22 19:09

calterras