Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace live() with on()

Tags:

jquery

From the documentation

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

I'm using jQuery 1.7.1

This works, for static elements and dynamically loaded elements:

$("input").live("change", function () { alert("hello"); });

This doesn't work, not even for static elements:

$("document").on("change", "input", function () { alert("hello"); });

What am I missing?

like image 278
user247702 Avatar asked Jun 10 '26 06:06

user247702


1 Answers

Write it like

$(document).on("change", "input", function () { alert("hello"); });

You can replace document with any closer parent element which will always exist in DOM for better performance. Like

$('#closest_static_container_id').on("change", "input", function () { 
     alert("hello"); 
});

if you use $("document") jQuery will search for a node/tag named as document like <document> and wont find anything as document is actually an object.

But you could use $("body") as body is a node/element of DOM.

like image 196
Prasenjit Kumar Nag Avatar answered Jun 11 '26 21:06

Prasenjit Kumar Nag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!