Posts Tagged ‘form’

Do NOT click that button!

Tuesday, January 5th, 2010

star5112 / flickr

Ever click on a button, decide you’re doing the wrong thing, and then move the mouse outside the button? I have, and when it’s implemented incorrectly, it drives me nuts.  It’s all due to using the JavaScript events onMouseDown and onClick incorrectly.

The button that won’t unclick: onMouseDown

Accidentally click the button below (click inside the button, then realize the horror of doing it, and then try to drag out of the button area):

This kind of button implementation annoys the crap out of me. There’s nothing you can do if you accidentally click the button, because by the time you realized you made a mistake, action already started. That’s because the button’s action is triggered by an onMouseDown event. Regardless of what happens next, that event is going to fire. So you cannot “cancel” the action by dragging the mouse out of the button and releasing the mouse button. The event has already fired and the action already started.

There’s a similar issue with the iPhone implementation of buttons. If you tap a button, but do not release, and drag out of the button, the button’s action will fire when you move outside the button. What’s interesting about this is that I cannot duplicate that scenario with a web browser. It appears that a onMouseUp event for a button is fired only if the mouse is still within the button, even if the corresponding onMouseDown event was inside the button.

The button that will click when it shouldn’t: onMouseUp

So that means it’s OK to use onMouseUp to trigger actions when a button is clicked, right? NO! With the button below, click outside the button, then drag to an area inside the button, and let the mouse button go:

The right way: onClick

While less annoying than the original button, it’s not correct behavior. A button should only have it’s action triggered if the mouse button is pressed and released within that button. That’s the onClick event, as implemented by this button.

Do both of the prior tests with this button. The only time you’ll see an alert is if you press the mouse button down, and then release it while inside the button. In fact, you can click inside the button, drag outside of it, drag back in, and then release the mouse button, and it will still work.

This is how your buttons should look in HTML:

<input type="button" value="Edit" onclick="javascript:theAction();"/>

Doing this means your buttons won’t fire too early. Also note that this isn’t an issue when using “submit” type buttons, as their behavior is automatically onClick.