Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - use existing handler for new elements

I've created table with inputs with onchange handlers to do some math; so for example:

jQuery(<selector will find many elements>).keyup(function (){do something})

Now there is a problem when I want to .append new table elements. They don't response to keyup... Is there a way to automagicaly bind new element (I'm using .clone) with existing .keyup (or any other event)?

like image 495
PsychoX Avatar asked Dec 27 '22 05:12

PsychoX


1 Answers

You should use event delegation. Event delegation takes advantage of the fact that events "bubbles" through the DOM, which means that many elements receive a notification of an event of one of its descendant elements.

With jQuery, this is even easier, since it smooths over some of the cross-browser inconsistencies of event handling and event bubbling.

Now, let's say that you want to bind an event handler to each row in a table. A straight-forward, but inefficient, way of handling this is to bind an event handler to each row. This is effectively what you are doing now. Imagine, instead, that you bind a single handler to the table, and say "Hey, invoke this handler whenever something happens to one of my rows". This is what event delegation is all about. With jQuery 1.7, the interface for event handling has been refactored and made more consistent. Here is an example of how to bind such a handler:

$('table.math').on(
  /*
   * This first argument is a map (object) of events and their corresponding
   * event handlers, like so: {eventName: eventHandler ([e]) {})
   */
  {
    keyup: function doMath (e) {
      // Your event handling code here. 
      // "this" refers to the input where the keyUp-event occured
    }
  },
  /* This argument is a selector, and reads: 
   * 'For table with class "math", bind to the events listed above
   * whenever a corresponding event occurs on an input with class
   * "mathInput"
   */
  'input.mathInput'
);

An additional benefit of event delegation is that it fulfills your criteria "there is a problem when I want to .append new table elements. They don't response to keyup". With event delegation this automatically works for all descendants that match the selector, whether they are present when the handler is bound, or inserted dynamically later.

To summarize, event delegation:

  • is more efficient. You bind a single handler instead of many
  • works for dynamically inserted elements
like image 176
PatrikAkerstrand Avatar answered Jan 11 '23 21:01

PatrikAkerstrand