DOM Level 3 Events support in IE9


Interoperable DOM Events are a core part of delivering the promise of HTML5’s “same markup.” With DOM Events support in IE9, web developers can write more interoperable code using an event model that is more robust and offers additional functionality not possible in IE’s previous model.


When authoring JavaScript event code for IE8 or previous versions, web developers have to branch their code specifically for IE. For example, most pages which employ cross-browser event code do so by using a completely separate code path:


if ( <addEventListener detect> ) {
// W3C DOM Event Model
// Supported by: Firefox, Chrome, Safari, Opera, and (now) IE9
}
else if ( <IE or attachEvent detect> ) {
// Previous IE Event Model code
}


Alternatively, web developers might use the “traditional” event model (HTML event attributes) since it offers the most interoperable functionality. However, this comes with a dramatic loss of functionality. The efforts of JavaScript framework publishers to patch browser differences between event models but often take a performance hit in doing so.


With IE9, you can write the same markup and script and have it work across browsers without sacrificing functionality or performance. Please follow best practices to ensure your standards-based event processing runs in IE9.  The Platform Preview will let you begin to see how your code will run in IE9.  We encourage you to report issues you find.  Since IE9 is still in development, the Release Notes and Connect bug database will help you understand if the issue you found is known.


“Same markup” through standards


Today developers can’t have the same markup run across browsers. IE9’s support of DOM Level 3 Events is a huge step forward but doesn’t entirely solve the problem. That’s why we’re working in the W3C to create a high-quality spec and create a test suite to help browsers converge on interoperable behavior.


For several years now, we have been working with the W3C standards organization to provide input and feedback on this latest version of DOM Events. When finished, this “Level 3” version will supersede its nearly 10-year old predecessor, DOM L2 Events. It’s been a pleasure to work regularly with members of that working group, representatives from industry, and other browser vendors to ensure that the specification is implementable, meets web developer scenarios, and raises the bar on interoperability.


There are two specific parts of the DOM Level 3 Events specification that I’m particularly excited about from the perspective of interoperability. The first is that IE’s “mouseenter/mouseleave” and “focusin/focusout” events have been recently adopted based on their utility and wide-use on the web.


The second is the Keyboard event interface. Did you know that the ubiquitous “keydown” “keyup” and “keypress” events (present in all browsers) were never standardized? This is an example of one of the reasons that web developers don’t have the “same markup” (script) running across browsers with regard to the keyboard.


The IE9 platform preview is the first implementation of the Keyboard event interface from the DOM Level 3 Events specification. The Keyboard event interface defines a Keyboard-interaction model that solves longstanding internationalization issues as well as provides a convenient high-level keyboard abstraction (based on Unicode). Naturally, we expect that previous low-level keyboard APIs (e.g., “keyCode”), despite not being 100% interoperable, will coexist in browsers for backwards compatibility. We welcome feedback on this interface, and for those interested in providing feedback directly to the working group, please email www-dom@w3.org


In our continued efforts to drive interoperability, we have contributed an initial set of tests for the DOM Level 3 Events specification and plan to contribute more in future updates to the Test Center. As the specification evolves toward recommendation status, these tests may also need to evolve. We look forward to feedback on these tests, and welcome test contributions from the community and other implementations to establish a DOM Level 3 test suite that meets the high interoperability goals of the specification.


Changes from the previous IE event model


As a whole, the DOM Events model (from both DOM Level 2 and Level 3 Events) solves many scenarios which the previous IE model is not equipped to handle. For example, the new DOM Events model enables the following scenarios to work interoperably across all browsers:



  • A “catch-all” listener can be registered on a DOM subtree for an event which does not bubble (requires capture phase).

  • Guaranteed firing order for multiple listeners on a single node.

  • Ability to tell which node the event flow is currently on (currentTarget).

As a result of supporting the new event model, IE9 standards mode makes a few changes to some existing events in the first platform preview build. (All of these changes are scoped to IE9 standards mode only.) For example:



  • The bubble/cancel defaults for many events have changed to match the standard.

  • Event listener registration for legacy events supported in the new model (using attachEvent/detachEvent) use the same event-firing order as addEventListener.

  • Registration using the HTML event attributes (and their properties) will simultaneously enable the MSEventObj (legacy event object) through the window.event property as well as the new DOM event via the event handler parameter. We do this because the HTML event attribute registration technique is ambiguous—e.g., did the web developer expect the new DOM Events model or the old IE one?

We built an interactive demo to showcase some of the features of the DOM Events model. Check it out on the IE9 Test Drive site. We also show a simple example of one way in which DOM Events can be used in practice. View it in the IE9 platform preview then view it in another browser; the key takeaway is that the DOM Events model works the same way across browsers—“same markup” in action.


More to come


We’re still in development so there’s more to come.  Here are a few top things you may find missing that will be available in a future update to the platform preview. Please read the Release Notes for further information.



  1. Mutation events. The mutation events allow web pages to react to changes in the structure of an HTML document such as changes in attributes, text content, element removals and additions, etc. The DOM Level 2 Events specification defines the mutation events. Note, however, that not all the mutation events are implemented across all browsers.

  2. DOMContentLoaded. The DOM Level 3 Events specification defines the generic event framework and a core set of events, but does not define all the events that are relevant for a web browser to support. HTML5 defines many additional events, most notably DOMContentLoaded and other events related to parsing and loading a webpage.

  3. Compatible event properties. While not standardized, many event properties like “keyCode”, “cancelBubble”, etc. are widely implemented by other browsers and many web pages depend on their functionality for purposes of interoperability.

We encourage web developers everywhere to start coding primarily to the DOM Event model. Check out the test drive demo and interactive events demo, the DOM Level 3 Events test cases, and send us feedback.


Thanks,
Travis Leithead
Program Manager

Comments (31)

  1. Anonymous says:

    "Did you know that the ubiquitous “keydown” “keyup” and “keypress” events (present in all browsers) were never standardized?" – Uh yeah we know that!

    1.) onkeypress in IE doesn’t capture the TAB key

    2.) no onkey…. events fire in IE on option elements

    3.) no onkey…. events can be registered in IE<9 using Elem.setAttribute(‘onkey….’, handler);

    but yes, blame the lack of a standard for the failing implementation – that way it looks like it was the "standards" fault.

  2. Anonymous says:

    Thanks, that’s very good news!

  3. Anonymous says:

    IE9 sounds like it’s shaping up very nicely.

  4. Anonymous says:

    Awesome news to hear!  It’s been a long time coming.  Now we’ll need a funeral for window.event (it was nice to know you).

  5. Anonymous says:

    So glad to hear that DOMContentLoaded will be in there.

    Now if we can get support for something like run_at capabilities from Google Chrome content scripts than I would be overjoyed. DOMContentLoaded is great, but being able to write a script to run between the DOM being loaded, but before scripts/images/etc are downloaded? That would be AWESOME.

  6. Anonymous says:

    @Brian LePore

    Wouldn’t this work?

    [html]

    [head]

    [/head]

    [body]

    [script]doBeforeDOMContentLoaded();[/script]

    [/body]

    [/html]

    Would this script tag just before the body close tag not run *after* the DOM content is loaded, but *before* all other scripts kicking in on DOMContentLoaded/onload event.

  7. Anonymous says:

    "Today developers can’t have the same markup run across browsers."

    Thanks to Microsoft and IE, which is why no one should use IE, including IE9 when it comes out, cause it, too, won’t allow us to have the same markup work across browsers despite what’s posted here.

    This is why IE market share has fallen from 95% to 52% in 5 years and continues to fall. These improvements in IE9 only bring it up to where every other browser was 3 years ago at best but IE9 won’t be out for almost 2 more years!

    You can’t fool us Microsoft.

  8. Anonymous says:

    That is a good news. I have seen in the release notes that you improved support for some areas of DOM Level 1 and Level 2. So, do you have any commitments on having full support for these (including passing the W3C DOM Level 1 and Level 2 tests)? So far, IE9 preview only shows a little improvement over IE8.

  9. Anonymous says:

    @Rob: If you think IE marketshare has fallen to 52%, you need to find a more reliable source for your statistics. IE is still twice as popular as all other browsers combined.

    You probably should also watch some of the demos, where the IE9 preview utterly destroys all of the other current version browsers in things that regular users care about (like video).

    @Brian: run between the DOM being loaded, but before scripts/images/etc are downloaded

    What would you do with that, if it wasn’t actually impossible?

    Modern browsers use parallel connections to download these things long before the DOM itself reaches a loaded state. Beyond that problem, by definition, script blocks that don’t specify "DEFER" are run as the DOM is constructed.

  10. Anonymous says:

    @Matt: while Rob goes at it a bit heavily, in some countries, IE actually went under 50%… Right now, in my logs on my websites, IE (all versions) is at around 65%.

    Which is still a 30+% drop in 5 years, and yes, it can be traced back to a lousy IE.

    I don’t agree with Rob as to IE 9 failing at catching up with current browsers. I do, however, hope that we won’t need to wait another two years before IE 9 engine quirks are solved (because, well, nobody’s perfect on the first try, and there will be quirks found after RTW) – other browsers do have the definite advantage of updating much more often.

    I don’t agree with you on IE 9 destroying the competition – it’s just that right now, with IE having finally caught back on DOM 2, CSS 2.1 and XHTML, there will be more widespread development done against those technologies, pushing them more, and on ‘new’ ones like DOM 3 and video. Shifting battlefield, but has IE 9 already won? Personally I’m not so sure.

    For one thing, IE 9 not supporting neither Vorbis nor Theora, sucks at media.

    I might understand not supporting Theora (after all, if forcing a $100 upgrade on users to get a new browser is a deal, forking over the money for an h.264 license is no big deal. Right?) since it is, admittedly, not as good quality-wise than the other.

    Not supporting Vorbis (which has been in fat, large productions by several software makers, including Microsoft for Halo – look, libvorbis.dll in the CD root), although it streams well (used by webradios all over the place for years), packs well (a 80 Kbps stream may not reach aural transparency, but it sure sounds much better than WMA – harmonics – or MP3 – muffling and ringing), (un)packs fast, and is flexible.

    Running after the DOM is loaded, but before images scripts etc. are loaded: it is possible, by using in-page code. The event used for that is DOMContentLoaded. It works very well. However, there is no other event firing between DOMContentLoaded and body.onload. It would be useful, sometimes, to have scripts running as soon as all external scripts are here (that can be achieved through a few hacks and shims; it’s not elegant, but it works) or when the whole lot of CSS are ready.

    This could be done in a more granular way by allowing page elements other than the body or framesets to fire an onload event, or equivalent (onload requires the node to load content; it seems IMG can handle it too, but LINK, SCRIPT, STYLE etc. can very well be empty, and thus be ignored; BODY, even when empty, is drawn to screen).

  11. Anonymous says:

    mitch, since you don’t understand why DOMContentLoaded doesn’t work like you think it does (and decline to accept correction regarding its relationship to script content) I wonder if maybe your remarks on Vorbis are similarly confused?

    In your last paragraph, are you asking for standardization of the onreadystatechange event?

  12. All we need now is to have the rest of the browsers start following standards. Nobody’s ever going to be able to write universally usable code until all the browsers that people use accept the same stuff and do the same stuff with it. I suppose I would be able to accept it if they didn’t follow standards if they still all did the same thing, but the best way to solve the problem would be to have everybody follow standards. Back when the browser wars started 20 years ago (or however long it was), I suppose I can see why everybody wanted to make their browser have extra stuff, but those were different times, now it should be pretty straight forward: next version, all standards supported. If everybody did that, then they could concentrate on usability and features instead of making their browser display stuff differently and frustrating users and developers, because nobody wants things displayed differently.

  13. Anonymous says:

    @njsokalski – you are joking right? First off, IE9 hasn’t shipped yet, so IE is still the farthest behind in terms of standards support of any shipping browser bar none.

    As for the other browsers, I’m sure they are hard at work filling any gaps with their implementations (after all, they were way ahead in implementing the standards that IE is only now catching up on)

    Think about it. IE for WinXP will NEVER EVER be close to standards compliant for its entire lifespan.  Thats well over a decade of IE failure.

  14. Anonymous says:

    @Matt: citing Mozilla.

    Fired on a Window object when a document’s DOM content is finished loading, but unlike "load", does not wait until all images are loaded.

    What didn’t I understand in this?

    onreadystatechange is already supported by all AJAX-able browsers. And as far as I know, XmlHttpRequest (which is the basis for AJAX) is at Working Draft state for the W3C dating back to 2006 (last updated in november 2009). So no, I’m not specially asking for it – it’s already underway.

    However, that event would have to be supported on the main window document (it is specified for a distant one, not a local one, which, until HTML 5 is done, isn’t the same thing) in order to be useful.

    And it wouldn’t help anyway, since readyState has only 4 return codes: 1 for ‘queried’, 2 for ‘headers received’, 3 for ‘loading’ and 4 for ‘done’; it doesn’t include anything for ‘document children loaded’.

    If you meant, checking the readystate of external CSS or script files, then no: you would have to check the status of all external CSS files, then all external script files. Which is a bit heavy.

    No, I meant allowing use of the onload event on any tag, meaning that an event fires once a tag (including all children) is done loading: imagine you have two big DIVs in your document, one including all your menus and links, the other including the page’s content. You may want to run some code right after the menu has completed, and not wait until the page’s content is done loading. If you want to put an event handler on the menu DIV, firing as soon as the menu is complete, you can’t.

    Something that could be done with framesets can’t be done with styled DIVs.

  15. Anonymous says:

    Finally, you’ve read the documentation, and learned that your prior remarks about DOMContentLoading firing before scripts are loaded were incorrect.

  16. Anonymous says:

    Awesome news! Its nice to see IE finally getting competitive shape. DOM L3 Events and DOMContentLoaded are very needed to be crossbrowser, so web will not trap itself (pun intended) in the js framework hell.

  17. Anonymous says:

    Great work guys on IE9 preview!

    But have a look at http://jhop.me/ie8-bugs. Hopkins collected a bunch of bugs on IE8, where most of them aren’t fixed in IE9 yet.

  18. Anonymous says:

    Travis, I can’t believe it !

    "We do this because the HTML event attribute registration technique is ambiguous—e.g., did the web developer expect the new DOM Events model or the old IE one?"

    How could you imagine developers expecting events firing in random order ?

    If you are sure this is what they expect you can shuffle() listeners on IE9 to maintain backward compatibility and give YOUR developers what they expect. Firing events in random order…the guy who wrote that had a great sense of humor.

  19. Anonymous says:

    Reading through the Release Notes, I can see that MouseEvent is supported. However, I see no mention made about pageX and pageY properties (which relate to mouse events, as they describe the position of the mouse cursor on the document). From my own tests, this is currently unsupported in the Preview, and wasn’t supported in previous IE versions

    IE requires the use of clientX/Y + document.body/documentelement.scrollTop/Left, or to make it simpler, detect the position on the viewport, then add the scroll position to determine the mouse position.

    For something that has to be recomputed on each mouse move, it’s rather tedious and CPU-intensive.

  20. Anonymous says:

    Great ! Will test that this week-end.

    What about document.evaluate ?

  21. Anonymous says:

    Now, before Matt gets on my case again, I know that pageX/Y is not DIRECTLY related to the mouse cursor; however, this is by far the most common use of these properties on an event object, since listening to other events makes no real sense – except if you wish to find a text cursor’s position in an input field (which has far more efficient properties at its disposal).

  22. Anonymous says:

    And yes, I KNOW this property isn’t part of any standard. It is however implemented by all browsers out there (but IE), and its standard equivalent (offsetX/Y on the body) is:

    – unsupported by Gecko

    – implemented incorrectly in Webkit and Presto

    – buggy in IE 6/7.

    Which makes it unusable in any practical way.

  23. Anonymous says:

    @Mitch74

    Regarding pageX and pageY properties: if IE9 aims to fully comply with CSSOM view module, then it will support pageX and pageY properties.

    CSSOM pageX and pageY properties

    http://www.w3.org/TR/cssom-view/#dom-mouseevent-pagex

    > pageX/Y is not DIRECTLY related to the mouse cursor

    pageX and pageY are DIRECTLY related to the mouse cursor; pageX and pageY are event properties and involve calculation starting from cursor position within initial containing block. Even if you do a keyboard event, the pageX/pageY properties for such event will still exist and be retrievable.

    > I KNOW this property isn’t part of any standard.

    It is now part of CSSOM view module. That’s why I asked Adrian Bateman if IE9 will fully comply with CSSOM view module

    > offsetX/Y (…) buggy in IE 6/7

    IE8 has an incorrect implementation of offsetX, offsetY. I reported it already:

    http://www.gtalbot.org/BrowserBugsSection/MSIE8Bugs/#bug65

    regards, Gérard

  24. Anonymous says:

    how to uninstall ie platform preview?

    thnx

  25. Anonymous says:

    @Gérard: well, I couldn’t find the W3C draft with pageX/Y in it, so I referred to quirksmode.org – which seemed to say that IE 8 had the only conforming implementation of offsetX/Y (by conforming, I mean referring to the borderless content, including padding – if the spec changed since IE 8 came out to reflect what earlier versions did, then it’s not exactly a regression, but more a case of a moving target).

  26. Anonymous says:

    IE6 and IE7 implementation of offsetX and offsetY were referring to padding-box not content-box. CSSOM first WD was released 13 months before IE8 RTW. So, it’s clearly a regression.

    regards, Gérard

  27. Anonymous says:

    @Gérard: yes, but the specification was (and still is) a working draft, far from final (getting close to Candidate, maybe). Previous definitions of offsetX and offsetY (or offsetleft/top) come from Mozilla and MSDN, and do not seem to include the padding.

    I would guess that this is the kind of discussion that goes on all the time on W3C mailing lists and in developer offices. Moving on.

    It doesn’t detract from the fact that pageX/Y support is sorely lacking. Now THESE ones, everybody agree on how they work: they refer to the viewport, thus borders, padding etc. don’t matter, whatever the box model used is.

    And it would be nice (not to say, lower the CPU drain) to have them in IE 9, because we would then FINALLY have a single way to determine the mouse cursor position on the page on ALL browsers.

  28. Anonymous says:

    > Previous definitions of offsetX and offsetY (or offsetleft/top) come from Mozilla and MSDN, and do not seem to include the padding.

    Mitch, this is why I rarely trusted MSDN documentation and always experimented. Empirical results and good testcase-ing are always so much more reliable+useful than what MSDN claims.

    > pageX/Y support is sorely lacking

    Agreed.

    >  (…) lower the CPU drain) to have them in IE 9, because we would then FINALLY have a single way to determine the mouse cursor position on the page on ALL browsers.

    Yes. I am all for IE9 supporting pageX and pageY properties. But one nuance. Getting just a few event properties on mousemove event (also on resize event) can easily put memory management and CPU activity under a lot of stress and will cause application crash on systems with modest resources. Abusing user system resources unneedlessly, excessively is very frequent in webpages/websites out there.  

    regards, Gérard

  29. Anonymous says:

    @Gérard: it’s because I don’t trust MSDN that I usually refer to Mozilla documentation first and foremost. But, for once, the two say pretty much the same thing. Now, I’d bet a penny for a pound that the definition actually changes depending on whether you use the content-box or border-box model (and IE has plenty bungs there, thus…). Careful testing is, indeed, required. And for that, I relied upon the tests done on these properties by Peter-Paul Koch for quirkmsode.org.

    A test done on browsers that support both approaches shows that pageX/Y can actually reduce CPU use by as much as 40% (using scroll+offset would max out at 34% CPU use on my old Sempron, using page would not go past 20% CPU use – note, the Sempron in question doesn’t change clock speed dynamically). That’s why I’d rather have pageX/Y.

  30. Anonymous says:

    As microsoft keeps losing the browser share…and it will continue to do so no matter how good ie9 is(it’s because of the 4 year update cycle)…why doesn’t microsoft rethink this process.

    As in…2 separate ie versions.You could call one Internet Explorer and the other Internet Explorer Insert_catchy_word_here.

    The other could only be available on this site(plus a really small link on the official site).

    This version would ofcourse contain ALL the "useless" junk that all the other browsers are throwing in.Like…WebGL and those little candies that make people switch just because of the "cool" factor.

    The problem ofcourse is they convince all their friends(and their parents get "used" to the other browsers as well)…thus contributing to the fall of ie’s market share.

    By the time even the most hard firefox or opera user will say "i actually like the new version of ie"…all his bloody family will be using the other browser and will not switch back simply because they’re "used" to it.

    A separate version of IE (cutting edge technology preview build) could fix this.

  31. Anonymous says:

    Are there any indications as to roughly when Internet Explorer 9 will be released, i.e. 2011 or 2012?

    My opinion of IE9 will be shaped to a large degree by how it copes with the small script below.

    Thanks

    Dave

    // Display an alert about whether browser claims poor DOM support or doesn’t support canvas/fillText()

    var msg = ”;

    ‘Core Events HTML HTMLEvents UIEvents’.replace(/w+/g,function(n){if (!document.implementation.hasFeature(n, ‘2.0’)) {msg += ‘ndocument.implementation.hasFeature(” + n + ”, ‘2.0’) returned false.’;}})

    if (!document.createElement(‘canvas’).getContext) {

    msg += ‘ndocument.createElement(‘canvas’).getContext returned false.’;

    } else {

     if (typeof document.createElement(‘canvas’).getContext(‘2d’).fillText != ‘function’) {

       msg += ‘nCanvas does not support fillText() function.’;

     }

    }

    if (msg !== ”) {

     alert(‘You appear to be using an out-of-date web browser.n’ + msg);

    } else {

     alert(‘Your web browser seems to have reasonable DOM and canvas/fillText() support.’);

    }