Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performant click and double click in jquery

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>
like image 634
neoDev Avatar asked Oct 20 '22 07:10

neoDev


1 Answers

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>
like image 104
tredzko Avatar answered Nov 03 '22 02:11

tredzko