jQuery: Attaching event handlers to non-existent elements

Prior to jQuery 1.7, there was a live() method which could be used to attach event handlers to non-existent elements.

Suppose you have an empty div, which you dynamically create links in later.

<div id="newLinks">
</div>

...
$('#newLinks').html("<a href='next.html'>click me</a>");

When the DOM first loads, there are no anchor tags so if you tried to bind an event handler to it, it will fail.

$('a').bind("click", function() {
  alert("clicked");
});

The above alert will never fire because the bind may be invoked before the anchor is added.

This was dealt with using the live() method which binds to elements that exist now or will exist later.

$('a').live("click", function() {
  alert("clicked");
});

However, as if jQuery 1.7, the live() method is deprecated, and even the use of bind() is discouraged. Instead, the on() method is preferred.

This is the preferred way to bind to an existing or yet-to-exist element.

$('#newLinks').on("click", 'a', function() {
  alert("clicked");
});

The above code will limit the method to look for anchor tags within the #newLinks div. This will be more performant than binding to all anchors on the page, unless that is the intent.

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: