JavaScript: onclick ondblclick on same element
May 01, 2011 21:40:35 Last update: May 01, 2011 21:47:18
It's a shame that double click events are always accompanied by click events in JavaScript. When you double click on an element, JavaScript fires two click events followed by one double click event. So if you attach both click and double click event handlers to the same element, both event handlers will be called when you double click.
This is a utility function to alleviate the problem somewhat:
Note that there's still a possibility that both clicks and double clicks fired at the same time. This is because the timer used above may not be identical to the double click timer configured at the OS level. It's impossible to fix this problem in application code since each user may configure double click speed differently.
This is a utility function to alleviate the problem somewhat:
- Code
- Demo
<!doctype html> <html> <head> <script type="text/javascript"> function addClickDblClickHandler(elem, clickHandler, dblClickHandler) { elem.onclick = function(event) { if (!this.timerStarted) { this.bufferedEvents = []; window.setTimeout(function() { // where the meat is // clean up buffered events var cleanedEvents = []; while (elem.bufferedEvents.length > 0) { var eventType = elem.bufferedEvents.pop(); cleanedEvents.push(eventType); if (eventType == 2) { // double click for (var i = 0; i < 2; i++) { eventType = elem.bufferedEvents.pop(); if (!eventType || eventType != 1) { break; } } } } // process events while (cleanedEvents.length > 0) { var eventType = cleanedEvents.pop(); if (eventType == 2) { dblClickHandler(event); } else { clickHandler(event); } } // reset timer elem.timerStarted = false; }, 300); this.timerStarted = true; } this.bufferedEvents.push(1); // 1 for single click }; elem.ondblclick = function() { if (!this.bufferedEvents) { this.bufferedEvents = []; } this.bufferedEvents.push(2); // 2 for double click } } </script> </head> <body> <button id="testButton">Click Me</button> <div id="status"></div> <script type="text/javascript"> addClickDblClickHandler( document.getElementById("testButton"), function() { document.getElementById("status").innerHTML += "click<br>"; }, function() { document.getElementById("status").innerHTML += "Double click<br>"; } ); </script> </body> </html>
Note that there's still a possibility that both clicks and double clicks fired at the same time. This is because the timer used above may not be identical to the double click timer configured at the OS level. It's impossible to fix this problem in application code since each user may configure double click speed differently.