September 2nd, 2005

Stop Event Bubbling on an Inline Function

Event bubbling is often overlooked and misunderstood.  Sometimes you don't want your event to bubble.  Luckly there are methods for disabling it, but just like everything cool online IE handles things differently than other browsers.  It gets tricker when you use inline event functions.

Being a lazy programmer I grabbed my standard cross-browser event bubbling prevention code. However, it didn’t work in Firefox, but it did work in IE. I thought this was pretty odd until I looked in the JavaScript debugger. In Mozilla based browsers and probably others, inline functions did not automatically pass an event parameter.

I changed my inline function, so the first paramater was the event object like so: <a href="#" onclick="doSomething(event, 1);">Link</a>,  And now my function looks like this:

function doSomething(e, i) {
e = (e) ? e : window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();

alert(i);
}

It works flawlessly. Take that event bubbling.