Bind events to future elements using jQuery’s .on()

· Leave a comment · in jQuery

I loved the feature of jQuery .live() binding to future elements – but it had problems.

It’s replacement, .on(), DOES NOT bind to future elements by default.

The following explains how to bind future elements using .on().

The jQuery .live() method is deprecated, replaced by .on().

The following two examples bind the click event to future elements using a different scope.

The first is a document scope. The second is a child scope.

jQuery
Document Scope

This example binds the click event to any future element added to the DOM with a class of “some-class”.

$(document).on("click",".some-class",function(){
//do something
})

Child Scope

This example binds the click event to any future element added to the DOM with a class of “some-class”, but only if a child of the element with an id of “menu”.

$("#menu").on("click",".some-class",function(){
//do something
})

See the full working example here.

Great books are available on JavaScript and jQuery.

Tested in:
jQuery 1.7.2+
FF 3.6+, Safari, Chrome, IE8+, iOS

This entry was posted in jQuery and tagged .
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

To include code in your comment: Paste your code in the comment form, select it and then click the language link button below. This will wrap your code in a <pre> tag(or shortcode) and format it when submitted.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">