Today I had the opportunity to play with event bubbling and applying generic event handlers. Quick overview on handling them (with jquery!) and which events cannot be cancelled.
Why use generic handlers?
If you are making a dynamic document, you know that CSS settings are applied as entries are inserted. If you dynamically create a div with class="foo", and you have a ".foo" style defined in your stylesheet(s), then it will inherit it automatically.
If you bind to every class="foo" element on a page at some point (say, with $(".foo").bind() with jquery), then append more elements with that class, they do NOT automatically inherit the event binding.
How to get around it
To get around this shortcoming, you can bind your event handler to a higher level event. I'm going to describe it with jquery. For example, let's assume you want to check for clicks on all divs with a class "foo", and make the background color red.
Here's the 'old' way with jquery:
$(".foo").bind("click", function(e) { $(this).css({'backgroundColor': 'red'}); });
The problem is, if you add a new div into the DOM, it will not have that event binding.
Here's the 'new' way:
$(document.body).bind("click", function(e) { var $target = $(e.target); if ($target.is(".foo")) { $target.css({'backgroundColor': 'red'}); } });
Pretty simple, right? Actually, it is. And it's less code and less of a pain than all the code required to bind new elements coming in most likely. Here's the code at work. Elements with class foo are bound to change bgcolor to red when clicked:
What can go wrong?
The major problem is events that don't bubble up. The wikipedia entry on DOM events has a nice list of events with their Bubble property - among those that don't bubble up: load, unload, focus (which was the one that prompted me to investigate), blur, DOMNode(RemovedFrom|InsertedInto)Document, rowexit, and others.
Still, this is an awesome technique. The more you make your page dynamic, the more useful it becomes.

FYI, $().bind('click') == $().click().
FYI, $().bind('click', function() {}) == $().click(function() {}).
Yeah, I knew that. :) Doesn't it feel like all those extra functions pollute the jquery object? Or is saving the keystrokes worth it? ;)
Thanks for the post. I badly needed it for my cisco exams project to complete.
Thanks once again :-)