mr r. mr r. - 11 days ago 5
Javascript Question

jQuery best way to apply eventhandlers

I'm working on a grid with 20 columns and 100+ rows. Every column has an input field. Now I want to put eventHandlers on the input fields like

change
and
keyup
,
focus
, and much more. So there can be 20*100 events = 2000!

What is the best way to do this? I've read something about eventHandlers and memory problems.

This is how I think I should do it:

$("#grid input").each(function() {
$(this).keyup(function() {
//
});
$(this).change(function() {
//
});
});


Or is this the best way to do it?

$("#grid").keyup(function() {
//
});

Answer

You're looking for event delegation.

$("#grid").on("change", "input", function() {
    // Handle the event here, `this` refers to the input where it occurred
});

That attaches one handler (on #grid), which jQuery then fires only if the event passed through an element matching the second selector. It calls the handler as though the handler were attached to the actual input. Even events like focus that don't natively bubble are supported through jQuery's mechanations.

More in the on documentation.

Comments