Yehuda Katz is a member of the Ember.js, Ruby on Rails and jQuery Core Teams; he spends his daytime hours at the startup he founded, Tilde Inc.. Yehuda is co-author of best-selling jQuery in Action and Rails 3 in Action. He spends most of his time hacking on open source—his main projects, like Thor, Handlebars and Janus—or traveling the world doing evangelism work. He can be found on Twitter as @wycats and on Github.
Event Normalization in jQuery 1.1.3
July 3rd, 2007
A loooong time ago, I wrote a bunch of event normalization code as a plugin to jQuery. In essence, the goal was the get events as close as possible to the DOM specification while retaining a sane file-size and backwards compatibility with existing code.
I wanted to add support for:
* relatedTarget, which, on mouse movement, returns the element that the mouse was previously on when moving onto or off of an element
* “which” for key events, which would return a normalized keyCode
* metaKey, which would return the Apple key on OSX, and the ctrl key in Windows (allowing stuff like apple-B to render something bold in OSX, but ctrl-B to do the same in Windows… the expected behavior)
* And a biggie: “which” support for buttons (1 for left-click, 2 for middle-click, and 3 for right-click).
I originally had some more grandiose plans, like supporting offsetX across browsers and getting keyCode to be the same cross-browser on keypresses, but those ended up either requiring unacceptable dependencies or requiring lots of messy code to get working.
Today, jQuery merged relatedTarget, which (for keys and buttons), and metaKey into the core jQuery distribution, and we did it without adding a single byte to the current 20k cap on jQuery’s filesize. We also added a whole slew of new features, without sacrificing our current cap. I say it’s incredible, and thanks to the hard, tireless work of the jQuery Core Team. The speed improvements, which are the work of jQuery’s maintainer, John Resig, also happened, sort of unexpectedly, without busting the 20k.
Back to the event normalization, I think you’ll find that between the old normalization that was present since the early days (event.target and event.pageX/pageY), and this new code, you’ll be able to do all sorts of neat tricks without having to put much thought into browser compatibility issues.