using jQuery live() to cross the DOM-HTML chasm

7 Nov

There’s a lag each time you use innerHTML – or the jQuery equivalent
HTML() – to set content. It won’t always be ready by the time the next
Javascript line executes.

$(“#container”).html(“start);
$(“#container button”).click(start);

The above code may fail to set up the event you wanted. Instead, you
can use the jQuery 1.3 live() command:

$(“#container button”).live(“click”, start);

The main intention of live() is to register events on objects that are
yet to be created. In this case, though, we are /sort of/ creating it
before live(), but we can’t guarantee it’s created yet. If you wanted
to be highly efficient, you could use a custom event handler instead,
which is what I had before I refactored to live():

(function wireButton() { $(“#container button”).length ?
button.click(start) : setTimeout(wireButton, 500); })();

live() is a nice quick fix. In this case, I’m using it for a modal
dialog, so I’m not too fussed if it adds processing overhead.
(Although if millions of people were using it, it would not be a very
environmentally-friendly modal dialog.)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: