Event bubbling in Javascript

| | Comments (3) | TrackBacks (0)

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.

0 TrackBacks

Listed below are links to blogs that reference this entry: Event bubbling in Javascript.

TrackBack URL for this entry: http://www.mattwallace.net/mt-tb.cgi/88

3 Comments

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? ;)

Leave a comment

September 2010

Sun Mon Tue Wed Thu Fri Sat
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    
Creative Commons License
This weblog is licensed under a Creative Commons License.

About The Author

Matt Wallace is a cloud computing architect, and recovering Web Application Developer working on a large e-commerce site and dabbling in social networking applications. He has recurring dreams of manipulating the real world with jQuery.