I’m looking to add a click handler to a div. But is there a way to use a single click handler function and share it between multiple divs? Since I may have 100 divs, I don’t want to create a click handler for each (they’ll all practically do the same thing). The jquery example shows:
$("p").click(function () {
$(this).foo();
});
can we do something like:
$("p").click(myClickHandler);
function myClickHandler(source) {
source.foo();
}
?
jQuery’s
.delegate()method is a great way to go if you don’t want the overhead of hundreds of click events.It assigns one event to a container, which gets fired when the specified descendants of the container get the event.
Test the example: https://jsfiddle.net/jYKgm/210/
HTML
jQuery
This will assign one handler to the
#containerelement, and make it so that any descendantdivelements will trigger the handler.So if there are 500 descendant
divelements, they will all share the one event handler. –
.delegate()– http://api.jquery.com/delegate