0

Hi I am working on a click double-click event handler for my jquery ajax engine. The idea is that you can click or double-click a button. I wrote this myself but I don't see why it is not working.

this is the code:

$('body').on('click', '.double-click', function() {
    var that = this;
    var dblclick = $(that).data('clicks');
    if(!dblclick){
        dblclick = 0;
    }
    dblclick = dblclick + 1;
    $(that).data('clicks', dblclick);
    dblclick = $(that).data('clicks');
    console.log('click - ' + dblclick);

    if(dblclick > 1){
        $(this).data('clicks', 0);
        //ajaxloader(this, 1);
        alert('dubbel-klik');
        console.log('dubbelcik event');
    }   

    setTimeout(function() {
        if(dblclick == 1){
            $(that).data('clicks', 0);
            //ajaxloader(this, 0);
            alert('klik');
            console.log('single click event');
        }
    }, 400);
});

It maybe looks a little over complicated but that is because I tried out some stuff. The problem I have is that when I double-click the double click the single click gets also executed. How is this possible when I reset with $(this).data('clicks', 0);. Then the counter has to be 0 and the if statement in the timeout has to be false.

Someone knows what is going wrong!?

O yes see a working demo here: click the click en dubbelclick button

botenvouwer
  • 4,334
  • 9
  • 46
  • 75

1 Answers1

2

You're overcomplicating this. jQuery has all of this built-in:

$('body').on('click', function(){ 
    alert("single click")
});
$('body').on('dblclick', function(){
    alert("double click");
});

This will also click the single though: you might want to check out this thread to see what you could do to prevent that: Javascript with jQuery: Click and double click on same element, different effect, one disables the other

Community
  • 1
  • 1
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • I want to use the two on the same elements. that does not work so that is the reason I wrote my script which by the way is just as complicated if you compare with the scripts I find behind the link you give me. – botenvouwer May 03 '13 at 20:54
  • Well, you can take a look at those scripts. Since they work you will find your answer in there. We could copy their answer here, but it's better you take a look at how they solved it. – Kenneth May 03 '13 at 20:56
  • Well you are welcome I already fixed it. I shall remove my question because it already exists. – botenvouwer May 03 '13 at 21:02