How to use both onclick and ondblclick on an element?

Viewed 54076

I have an element on my page that I need to attach onclick and ondblclick event handlers to. When a single click happens, it should do something different than a double-click. When I first started trying to make this work, my head started spinning. Obviously, onclick will always fire when you double-click. So I tried using a timeout-based structure like this...

window.onload = function() {
  var timer;
  var el = document.getElementById('testButton');

  el.onclick = function() {
    timer = setTimeout(function() { alert('Single'); }, 150);        
  }

  el.ondblclick = function() {
    clearTimeout(timer);
    alert('Double');
  }
}

But I got inconsistent results (using IE8). It would work properly alot of times, but sometimes I would get the "Single" alert two times.

Has anybody done this before? Is there a more effective way?

6 Answers
,   cellclick   :   
        function(){
            setTimeout(function(){
                if (this.dblclickchk) return;
                setTimeout(function(){
                    click event......                   
                },100);
            },500);
        }

,   celldblclick    :   
        function(){
            setTimeout(function(){
                this.dblclickchk    =   true;
                setTimeout(function(){
                                          dblclick event.....
                },100);
                setTimeout(function(){
                    this.dblclickchk = false;
                },3000);
            },1);
        }

I found by accident that this works (it's a case with Bing Maps):

                 pushpin.clickTimer = -1;
                  Microsoft.Maps.Events.addHandler(pushpin, 'click', (pushpin) {
                    return function () {
                        if (pushpin.clickTimer == -1) {
                            pushpin.clickTimer = setTimeout((function (pushpin) {
                                return function () {
                                    alert('Single Clic!');
                                    pushpin.clickTimer = -1;
                                    // single click handle code here
                                }
                            }(pushpin)), 300);
                        }
                    }
                }(pushpin)));
                Microsoft.Maps.Events.addHandler(pushpin, 'dblclick', (function (pushpin) {
                    return function () {
                        alert('Double Click!');
                        clearTimeout(pushpin.clickTimer);
                        pushpin.clickTimer = -1;
                        // double click handle here
                    }
                }(pushpin)));

It looks like the click event masks the dblclick event, and this usage is clearing it when we add a timeout. So, hopefully, this will work also with non Bing Maps cases, after a slight adaptation, but I didn't try it.

Related