The intent of this code was create a performant click
and double click
action,
but it actually work very bad... It is not very performant at all, so I would like to know a better way to do it
In this way I completely lost the sensibility of the single click, and now it is only delayed,
and also the double click is not very brilliant..
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>
Your code looks mostly fine. One of the problems of dealing with clicks and double clicks is you'll have to show one result before the other. Otherwise, you have to impose a delay for people who single click.
The code below simply moved your $('button').html("Single Click");
outside of the timer function, so it will make the button respond immediately instead of waiting to see if the user is double clicking.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With