Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  156] [ 6]  / answers: 1 / hits: 86170  / 13 Years ago, sun, december 11, 2011, 12:00:00

Since version 1.7 live is deprecated.



Following example is easy to make compatible with new on method:



$('nav li, #sb-nav li, #help li').live('click', function () {
// code...
});


Using on:



$('nav, #sb-nav, #help').on('click', 'li', function () {
// code...
});


How to rewrite following example using on?



 $('#header .fixed-feedback-bn, #sb-sec .feedback-bn').live('click', function () {
// code...
});

More From » jquery

 Answers
134
$(document).on('click', '#header .fixed-feedback-bn, #sb-sec .feedback-bn', function () {
// code...
});


.live() is just binding document as listener.



My two cents are that you can almost always find a better listener than document. At bare minimum, almost all pages use a main content wrapper. This eliminates nodes in the header, footer, and sometimes sidebars as listeners.



The best way to use .on as a delegating function is to identify the nearest common ancestor that is expected to never be destroyed or otherwise have events unbound. For example, if you have a form that gets updated and changed by ajax requests, the listener could be the form node itself (if only the contents of the form are updated) or a container element (generally a div) that surrounds the form. If such a div isn't there, you could always add it in, or you could just go up the tree to the next ancestor.



[edited to add:]



In the particular sample code provided, it's hard to say if there's a better listener that would contain both #header and also #sb-sec. But imagining that these things share an ancestor with the id mainContainer, your more efficient code simply swaps out the listener:



$('#mainContainer').on('click', '#header .fixed-feedback-bn, #sb-sec .feedback-bn', function () {
// code...
});

[#88621] Friday, December 9, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryonk

Total Points: 161
Total Questions: 116
Total Answers: 107

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
bryonk questions
;