So, Let’s say there is a text field and a button. We have an event handler for text field’s ‘blur’ event and there is a ‘click’ event handler to the button. On blur event of the textfield, we remove the textfield from the DOM tree, which internally adjusts the page layout moving the location of the button on the screen. So, what happens to the event handlers for the text field & button?
I have created a jsFiddle for this exercise and following are the steps to run this test case. Thanks to my colleague for short & simple code for this jsFiddle :).
1.) Place the cursor focus on the textfield
2.) Without tabbing out or clicking anywhere on the screen, just click on the button
3.) Observe the console output on the textarea.
If you are surprised as I was, you would see the console output from ‘blur’ event but, not from the ‘click’ event. The reason is, mouse ‘click’ event is triggered only after the successful completion of ‘mousedown’ & ‘mouseup’ events sequence on the exact same component.
So here in this example, when we click on the button, ‘mousedown’ is triggered which internally triggers ‘blur’ event on the textfield. And right after that, button’s location is changed from the screen(because of the textfield being removed) and ‘mouseup’ could not be triggered as the mouse pointer’s location is not within the bounds of the button.
My original argument was, as long as we have a click event handler attached to the button, it should be fired irrespective of where the button resides on the page. But, that is simply not true as we had just proved.
After digging into this little further, I was able to find out where this expected behavior is actually mentioned. To my surprise, I was able to find the fine print both in jQuery’s click event & W3C’s mouse event API doc.
jQuery’s click event API doc – http://api.jquery.com/click/
The click event is only triggered after this exact series of events:
The mouse button is depressed while the pointer is inside the element.
The mouse button is released while the pointer is inside the element.
W3C’s mouse event doc – http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MouseEvent
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. The sequence of these events is: