Thursday, June 3, 2010

DOM Events for HTML Radio Buttons

An interesting bug came up today, and it had to do with the way IE 8 processes DOM events differently than the other browsers.

Here's the scenario:

We were attaching to a radio button's onchange event to do some processing. When you click on an option, we show you a particular div relevant to your selected option. This worked just fine on Firefox and Chrome, but was wacky on IE8. It turns out that IE8 doesn't seem to fire the onchange DOM event until after the element *loses focus*, meaning that our divs didn't show up until we clicked somewhere else on the screen.

We fixed the issue by switching to the onclick event, which fires nicely, on the click, as you would expect, on all three browsers.

In summary: when you want to trigger something when a user selects one of your radio buttons, attach to the onclick event, and not the onchange event, which has variable behavior across browsers.

No comments: