Click and double click in jquery

The purpose of this code was to create the click action and double click executor,
but it actually works very poorly ... It's not very good at all, so I would like to know the best way to do this.

Thus, I completely lost the sensitivity of one click, and now it only lingers,

as well as a double click is not very close.

 var DELAY = 150, clicks = 0, timer = null; $(function(){ $('button').on("click", function(e){ clicks++; if(clicks === 1) { timer = setTimeout(function() { $('button').html("Single Click"); clicks = 0; }, DELAY); } else { clearTimeout(timer); $('button').html("Double Click"); clicks = 0; } }) .on("dblclick", function(e){ e.preventDefault(); }); }); 
 button { padding: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button>click Me</button> 
+5
source share
2 answers

Your code looks mostly beautiful. One of the problems associated with clicks and double clicks is to show one result in front of another. Otherwise, you should impose a delay for people who click once.

The code below just moves your $('button').html("Single Click"); outside the timer function, so it will immediately respond to the button, and not wait if the user double-clicks.

 var DELAY = 350, clicks = 0, timer = null; $(function(){ $('button').on("click", function(e){ clicks++; $('button').html("Single Click"); if(clicks === 1) { timer = setTimeout(function() { clicks = 0; }, DELAY); } else { clearTimeout(timer); $('button').html("Double Click"); clicks = 0; } }) .on("dblclick", function(e){ e.preventDefault(); }); }); 
 button { padding: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button>click Me</button> 
+3
source

What is great about you, I would say that there really is no way to improve this, how logical it is. The only way would be to lengthen the delay so that it becomes more accessible. Older people sometimes click mice more slowly ...: P

Your delay: http://jsfiddle.net/0928paqh/1/

Longer delay: http://jsfiddle.net/0928paqh/2/

Long enough for slower users, but not long enough to annoy anyone.

0
source

All Articles