Wednesday, September 11, 2013

A simple mouse click, not easy mouse event

My very first task in my job is to code refactoring the UI widgets developed by our company (mainly some mutation of jquery UI). Through studying the current UI widgets' life cycle, I found that most of the bugs were came from mishandling of mouse events. After the hard studies of the behaviors across the 3 main browsers, IE, Firefox and Chrome, I have a small note and summary as below.
Include the jquery custom focusin and focusout events, there are total 8 events which are trigger by a Single Mouse Click, and they are: mousedown, mouseup, focusin, focusout, focus, blur, change and click. Actually only the first two events, mousedown and mouseup, are directly related to the physical mouse left button press and release, all others are some logical events. As excepted, different browsers has its own implementation, but surprisingly different jquery version handle the events differently, as the result jquery dosen't help you to standardize the event sequences, and make things so unexpected. But after thousands of tests and experiments, I figuer out the evnet sequence should like:
1) mousedown -> 2) change(A Type) -> 3) focusout -> 4&5) blur / focusin -> 6) focus
7) mouseup -> 8&9) change(B Type) / click
This sequences is generalized for all focusable and editalbe elements, such as a button, input box, radio button, div with tabindex, etc. Lets assume A Type element is something like input box and textarea, and the B Type element is something like check box, radio button and select list. With this knowledge, there are several thing we shoud be care.
  1. The event sequence would always preserve, which means they are always fire out one by one, even if you had call preventDefault and stopPropagation. But if you call preventDefault during mousedown, the 2nd to 6th events would not be fired.
  2. blur and focusin event would come out dependent on browser, normally it is blur -> focusin, in IE it is focusin -> blur, so you should choose only one of them to use in the whole system, to prevent logic error or dead lock between elements.
  3. For B Type elements, the change and click event sequece is also dependent on browser, IE8, IE9+, Firefox and Chrome would have totally different strange behaviors. If you use jquery to bind event handlers, the intermediate element's value would be different also. You must bind handler to change event, if you need to trace the element's intermediate value.

No comments:

Post a Comment