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?
So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
To create an element with an onClick event listener: Use the document. createElement() method to create the element. Use the addEventListener() method to add a click event listener to the element.
The ondblclick attribute fires on a mouse double-click on the element.
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.
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