Converting From jQuery’s .live() to .on()

December 15th, 2012 - Posted by Steve Marks to Javascript / jQuery, Web Development.

If you’ve ever updated the DOM’s contents manually using JavaScript (ie. with the response from an AJAX call), and then wanted to manipulate this updated content, you’ve no doubt needed to use the jQuery .live() function.

As of version 1.7 of jQuery however, the .live() function has been deprecated. If you’re using a version of jQuery newer than this, or if you’ve recently updated, your code will still work, but it’s recommend you change over to use .on() instead.

So, how do we do this? Let’s imagine that have the following code that incorporates .live():

<script src="jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function() {
	
	$('#outerDiv').html('<input type="button" />');

	$('button').live('click', function() {
		alert( 'Hello World' );
	});

});

</script>

<div id="outerDiv"></div>

In running the above, a button will added to our div which, when clicked should give us an alert containing the words ‘Hello World’.

Now let’s look at the same code, but use .on instead:

<script src="jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function() {
	
	$('#outerDiv').html('<input type="button" />');

	$('#outerDiv').on('click', 'button', function() {
		alert( 'Hello World' );
	});

});

</script>

<div id="outerDiv"></div>

Note that the primary selector, in our case ‘#outerDiv’, is an element that must be present when the page loads. The element that we manually added to the DOM and that we’re wishing to interact with then goes as the second parameter of the call to .on().

This entry was posted on Saturday, December 15th, 2012 at 12:56 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (1)
  1. property of 0). In previous versions of jQuery, this would return a set containing the document node.