Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is the difference between .live and .on event in Jquery? How easily you can update old .live event to new jquery .on event?

user-image
Question added by Ali Imran Ahmad , Frontend Web Developer , SheenSol Technologies
Date Posted: 2014/11/03
Alaa M. Jaddou
by Alaa M. Jaddou , CEO , Aj Design & Develop

 

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Equivalent to .live() would be something like

$(document.body).on('change','select[name^="income_type_"]',function(){ alert($(this).val());});

Although it is better if you bind the event handler as close as possible to the elements, that is, to an element being closer in the hierarchy.

Update: While answering another question, I found out that this is also mentioned in the .live documentation:

Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

$(selector).live(events, data, handler);// jQuery1.3+ $(document).delegate(selector, events, data, handler);// jQuery1.4.3+ $(document).on(events, selector, data, handler);// jQuery1.7+

Ata Mustafa
by Ata Mustafa , Senior Software Engineer and Team Lead , Vizteck Solutions

.live() is deprecated in jquery version1.7 and removed from1.9. It is replaced by .on() function.

 

The way which i use to handle your scenario is like as follows:

- Put your jquery code in a separate function let say callFunc(); 

- Check current version of jquery by using $().jquery

- if it is less or equal to1.7 then use live like as follows

$("#button").unbind("click").live('click', callFunc);

 

- and if it is greater than1.7 then

$(document).on('click', '#button', callFunc);

 

I hope it helps

Cheers

Ata

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.