Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .on versus .live

Tags:

I know that .live() is now deprecated but I cannot seem to change it and keep the functionality.

I just have a quick question about the .on() function in jQuery. I'm currently using .live() here

Like so:

$('table tr th').live("click", function() { }); 

But, when I try and replace .live() with .on() it no longer works as it's supposed to.

I've tried putting in

$('table tr th').on("click", function() { }); 

as well as

$('table tr').live("click", "th", function() { }); 

and

$('table tr').delegate("th", "click", function() { }); 

but to no avail.

Why is this and what steps can I take to make it work properly?

like image 418
ayyp Avatar asked Dec 12 '11 16:12

ayyp


People also ask

What is the use of .on in jQuery?

The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree.

What is .live in jQuery?

jQuery live() Method The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur. Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).

What is the difference between bind () and live () method in jQuery?

In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future. The underlying difference between them is that live() makes use of event bubbling.

How do you call one event from another event in jQuery?

$('#b1'). on('click', function(){ $('#select_item'). trigger('change'); }); $('#select_item'). on('change', function(){ var jbyr = $(this).


2 Answers

The on() function requires a syntactical update, you should alter your code to:

$('body').on("click", "table tr th", function()... 

Check out this article for more info: http://www.andismith.com/blog/2011/11/on-and-off/

like image 84
Tom Walters Avatar answered Dec 12 '22 17:12

Tom Walters


Try this:

$('table tr th').live("click", function() { 

should be

$(document).on("click", "table tr th", function() { 

That is how you would mimic the .live call exactly. You could of course limit your selector from document to something more meaningful based on your DOM structure.

Edit:

Just to clarify, in your example, you are required to use $(document).on(... because the table doesn't have any parents and is replaced during the life of your page.

like image 32
Kevin B Avatar answered Dec 12 '22 18:12

Kevin B