tl;dr: For direct swap-in replacement (accounts for dynamic loading), see the General Example below.
As other posters have noted, the accepted answer works, but $(#MainDiv')
needs be a "non-dynamic element (not being loading again through ajax)". This is preferable performance-wise, as the event bubbling "distance" is limited. In the example, it only needs to bubble up to it's parent element to be handled.
The solution would be to bind to the "parent-most" element that is not going to be reloaded (via AJAX usually) - in the example, you'd need to bind to $('#MainDiv')
's parent.
However,
If you do want a direct swap-in replacement for live()
, all you need to do is bind to the document
element instead.
Generic examples
format 1:
//Replace:
$(selector).live(events, handler); // Where `events` is a string
//With:
$(document) .on(events, selector, handler);
format 2:
//Replace:
$(selector).live(events); // Where `events` is
// an object of `handler`s
//With: // (as in OP's example)
$(document) .on(events, selector);
Note that with the on()
examples,selector
's container(s) can change and the binding will be automatically applied; the same functionality as live()
.
OP's example (format 2)
//Deprecated live() version:
$('.MyTextBox').live({
mouseenter: function () { .... },
mouseleave: function () { .... },
blur: function () { ... }
});
//New on() version
$(document).on({
mouseenter: function () { .... },
mouseleave: function () { .... },
blur: function () { ... }
},'.MyTextBox');
.live()
and.delegate
do the same basic thing (event delegation, by testing the event target when events bubble up). The difference is that.live()
catches events all the way up at the document level, whereas.delegate()
will catch them wherever you specify (i.e. closer, which is better). So, the.on()
equivalent of.live()
is$(document).on('event', '#selector .you > would've ~ used [with=live]', fn)
. Otherwise,.on()
works like.bind()
or.delegate()
, depending on whether or not you provide a selector as the second argument. – Unthinking.live()
doesn't attach new handlers when elements are added to the DOM. When you write something like$('.targets').live('click', fn)
what actually happens is jQuery begins monitoring click events that bubble up to the document object, checks to see if their eventTarget matches.targets
, and executes your function if they do. It uses exactly the same approach that.delegate()
does, but with less flexibility to catch the bubbling events closer to where they occur. Using$(document).on('click', '.targets', fn)
does the same thing. – Unthinking