$(document).on('click', '.selector', function() { /* do stuff */ });
EDIT: I'm providing a bit more information on how this works, because... words. With this example, you are placing a listener on the entire document.
When you click
on any element(s) matching .selector
, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation()
method -- which would top the bubbling of an event to parent elements.
Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.
This is smart for a few reasons, including performance and memory utilization (in large scale applications)
EDIT:
Obviously, the closest parent element you can listen on is better, and you can use any element in place of document
as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.