How to use both onclick and ondblclick on an element?

Josh Stodola picture Josh Stodola · Oct 9, 2009 · Viewed 49.3k times · Source

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?

Answer

Soldarnal picture Soldarnal · Oct 9, 2009

Like Matt, I had a much better experience when I increased the timeout value slightly. Also, to mitigate the problem of single click firing twice (which I was unable to reproduce with the higher timer anyway), I added a line to the single click handler:

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

This way, if click is already set to fire, it will clear itself to avoid duplicate 'Single' alerts.