In the old days, I used to chain calls to live() with great success, e.g.:
$(".something") .live("click", function(e) { ... }) .live("change", function(e) { ... }) .live("submit", function(e) { ... }); These days, live(), bind() and delegate() have been superseded by the shiny new on().
I've tried simply replacing live() with on() which would seem obvious:
$(".something") .on("click", function(e) { ... }) .on("change", function(e) { ... }) .on("submit", function(e) { ... }); However, it's almost as obvious that this won't work when you consider how on() works. This from http://api.jquery.com/on/:
"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()."
According to the jQuery docs, I need to bind to document and delegate to .something to handle live events. Unfortunately, this means I end up repeating my delegate selector (.document) if I want to replicate what I have above with on():
$(document) .on("click", ".something", function(e) { ... }) .on("change", ".something", function(e) { ... }) .on("submit", ".something", function(e) { ... }); This works as expected but I'd really love to be able to chain more clearly like I do using live(). Am I missing something?
I believe you can do this:
$(document).on({ "click" : function(e) { ... }, "change" : function(e) { ... }, "submit" : function(e) { ... } }, ".something"); That is, use the "events-map" syntax to specify the events and their handlers, and then specify the selector to use for the delegate-style behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With