Monday, October 11, 2010

Double-Click Detection in IE and Other Browsers

Several months ago, I wrote some code for cross-browser support for double-click detection. It was sort of tricky to put together, so I should I have posted it, but I forgot. But here it is:

function hookIEDblClickToClickCatcher(object, handler)
{
var isDown = false;
var isMismatchedUp = false;
object.onmousedown = function() { isDown = true; isMismatchedUp = false; };
object.onmouseup = function() { if (isDown) isDown = false; else isMismatchedUp = true; };
object.ondblclick = function() { if (isMismatchedUp) { handler.call(this); isMismatchedUp = false; } };
object = null;
}


The general idea of this code is this. You might add an onclick handler to some HTML element in JavaScript. But then you notice that, in IE, if people click an object repeatedly (like in a game), every 2nd click counts as a double-click and is ignored. So you want to register a double-click handler and have that also trigger a click event.

The problem is that this results in too many clicks for non-IE browsers. Other browsers trigger both a click event and a double-click event on the second click of a double-click, so in total your click handler ends up triggering three times. So what you want is a way to trigger a click handler on a dblclick for IE only (but you don't want IE specific code in case IE changes its behavior in the future).

Fortunately, IE has a distinctive sequence of mouse down and mouse up events that lets you detect an IE double-click vs. the double-click of other browsers (there is no mouse-down event before the double-click event).

1 comment:

  1. Brilliant! Works perfectly! Thanks for posting.

    ReplyDelete