I'm having a really weird behaviour on a form.
There is a number of text fields with in-line validation, showing an error message below the field if the content is invalid. The validation is triggered on blur.
At the bottom of the page there is a "Next" button. On click, a validation is performed and, if everything is ok, the form is submitted.
Now, if a mandatory, empty field has focus when I click the button the following happens:
- onBlur is triggered and in-line validation is performed
- the error message is displayed
- the rest of the page is "pushed down" to show the error text
- the onClick action on the button is NOT triggered
I initially thought that onBlur was somehow preventing onClick. Then I've noticed that when the page moves down, the mouse pointer is no more ON the button as this is pushed down. If I click on the button in a low enough position, such that after the "moving" the pointer is still on the button, onClick is triggered.
I replaced the onClick with onMouseDown and the problem is fixed, but I am really puzzled by the reason this happens.
The onClick
doesn't trigger because there hasn't been a click - a click is a mousedown
followed by a mouseup
on the same element. If the mouse is no longer over the same element, the browser can't consider it to be a click - I believe this even fails to become in some cases when the mouse moves (try a link and move the mouse, see if it still follows the link), though at least in my testing scrolling with the mouse down still keeps it as a click if you scroll back.
From http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mouseevents:
The click event occurs when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location.
In your case, while the mouse is not moving, the 'click' isn't occurring over 'an' element, or if there is just one element under the mouse, its the body element, and not what you had in mind.
As far as fixing this, you have several options:
- Don't scroll the page away while the mouse is down - this is almost certainly confusing/surprising to the user no matter what they were clicking on
- Don't require a click event, but use a mousedown (as it sounds like you are doing now)
- Slowly scroll to the new location, perhaps with a delay and an animated scroll so that a quick click would not be affected. Keep in mind however that buttons are supposed to respond to clicks, allowing the user to hold the mouse down and potentially change their mind by moving the mouseaway before they release.