Frontend Tips

Practical advice for frontend engineers / web developers

IE bug: change event ‘fails’ to bubble

By Isofarro on October 5th, 2009 - No comments

I ran into a weirdness where the change event fired on a select HTML element doesn’t seem to bubble up and reach the listener attached to the parent form element. Although this is specified in a W3C recommendation for this event to bubble, Internet Explorer doesn’t do this (but perhaps IE’s behaviour is correct?).

So I’ve have to assign a change event listener to each select in the form when they are available. And take care to keep doing that if additional selects are dynamically added later.

Internet Explorer doesn’t allow you to take advantage of event delegation on the change event. Which is a pity, since it’s an incredibly useful event in dynamic JavaScript functionality. But there is a logical rationale for this: This event is valid for INPUT, SELECT, and TEXTAREA. element.

The benefits of event delegation

Event delegation is a handy mechanism for adding a specific behaviour when a certain event fires for one of a group of similar elements. The technique is to listen for that event at a parent element level, and when that event happens and bubbles up to this level we check that the event happens on an element we care about and process it.

The advantage here is that we add one event listener to one element, rather than one event listener to a large or unknown number of elements.

The second advantage is that we can dynamically add extra elements as children of the listening parent, and they will take advantage of these pre-defined event handlers as soon as they are present in the DOM.

Some events bubble up the document tree, and some don’t. There are cases where it is not appropriate for a DOM event to bubble up to parent elements. The W3C DOM Events Recommendation covers which HTML events should or should not bubble.

Internet Explorer foibles

Internet Explorer goes it’s own way. It doesn’t recognise the change event on elements that aren’t changeable input fields, so listening to the change event at the form element level doesn’t work.

PPK has tested that IE doesn’t recognise change events on elements that are not input, select, and textarea. (Thanks for the correction PPK)

The main solution is not to use event delegation, and to assign listeners on the actual elements themselves. Quite a step backwards, with both a code maintenance and performance hit.

Add a comment or reply

Copyright © 2007 - 2009, isolani