views:

762

answers:

3

I'm handling both the click and dblclick event on a DOM element. Each one carries out a different command, but I find that when double clicking on the element, in addition to firing the double click event, the click event is also fired twice. What is the best approach for preventing this behavior?

A: 

In this case, it is best to delay the execution of the single click event slightly. Have your double click handler set a variable that the single click event will check. If that variable has a particular value, could be boolDoubleClick == true, then don't "fire"/"handle" the single click.

Jordan S. Jones
Actually, that's what I'm doing now, but it seems like it's a rather kludgy solution. I delay the click handler by 300 ms (a noticeable and annoying delay) and even with that you can still double click slow enough (eg. 350 ms) to make both of them fire.
David
Interesting. It isn't unreasonable to assume that if they delay too long for the second click that the desired effect would be 2 single clicks.
Jordan S. Jones
Unfortunately the double-click time is configurable by the end-user (e.g. using Control Panel/Mouse), and I suppose that JavaScript in a browser cannot get/determine what that time delay is configured as.
ChrisW
+3  A: 

In a comment, you said,

I delay the click handler by 300 ms (a noticeable and annoying delay) and even ...

So it sounds like what you want is that when you click then the DOM should geneate a click event immediately, except not if the click is the first click of a double-click.

To implement this feature, when you click, the DOM would need to be able to predict whether this is the final click or whether it's the first of a double-click (however I don't think is possible in general for the DOM to predict whether the user is about to click again).


What are the two distinct actions which you're trying to take on click and double-click? IMO, in a normal application you might want both events: e.g. single-click to focus on an element and then double-click to activate it.

When you must separate the events, some applications use something other than double-click: for example, they use right-click, or control-click.

ChrisW
Thanks for the updated answer. I think this really comes down to the fact that I need to rethink my UI. What I want to accomplish really isn't going to be possible. I should simply use two controls for the two actions, or use a modifier key instead of the double-click. Thanks!
David
A: 

AFAIK DOM Level 2 Events makes no specification for double-click. It doesn't work for me on IE7 (there's a shock), but FF and Opera have no problem managing the spec, where I can attach all actions to the click event, but for double-click just wait till the "detail" attribute of the event object is 2. From the docs: "If multiple clicks occur at the same screen location, the sequence repeats with the detail attribute incrementing with each repetition."