Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use both onclick and ondblclick on an element?

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?

like image 391
Josh Stodola Avatar asked Oct 09 '09 21:10

Josh Stodola


People also ask

Can an element have multiple onclick events?

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

Can you add onclick to any element?

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.

What does Ondblclick do in JavaScript?

The ondblclick attribute fires on a mouse double-click on the element.


1 Answers

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.

like image 114
Soldarnal Avatar answered Oct 01 '22 03:10

Soldarnal