Is there any way to delegate an event using jQuery that will correspond to all elements on the page that match the selector, other than delegating from $(document)
?
Since that's probably poorly worded, here's the rub:
There used to be jQuery.live
that delegated events to all elements that matched the selector. This was superseded by jQuery.delegate
which delegated events within a specific context selector to its children, which in turn was superseded by jQuery.on
, which does effectively the same thing, but with different bits behind the scenes (I'd imagine).
What I want to do, is safely add an event handler to every div.foo
on my page, regardless of where it might live, or when it might live. According to the documentation, and empirical research, the following will only bind to .foo
elements that exist when the script is run. Since there is code that might place a .foo
element on the page later, this doesn't exactly work.
jQuery('.foo').on('click', handler);
Since live
is deprecated (possibly removed?), I'm trying to not use that, but the only solution I can come up with is
jQuery(document).on('click', '.foo', handler);
But isn't this what live
did originally, behind the scenes? More to the point, are there any significant reasons not to do this?
We're specifically using version 1.7.2, but generic jQuery answers would help too.