Cover by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

8.10. Making Event Handlers Work for Newly Added Elements

Problem

You’ve bound one or more event handlers, and they suddenly stop working.

It happens after new elements are added dynamically by an Ajax request or simple jQuery operations (append(), wrap(), etc.).

Note

This problem is incredibly common, and we’ve all fallen for this at least once.

I’ll explain the theory behind it in the “Discussion” section. If you feel you need to understand this well before heading to the solutions, check Why do event handlers get lost ? first.

Solution

There are two possible solutions for this recurring problem, each with its own pros and cons:

Rebinding

This approach requires you to call bind() again and again, every time new elements are added.

It’s pretty easy to implement and doesn’t require any plugin or new method.

You can simply have all the bindings in a function and call it again after each update.

Event delegation

It relies on event bubbling.[15] This is fast and light but requires a little understanding and can be (just) a little tricky at times.

Since jQuery 1.3, there’s built-in support for event delegation. Using it is as simple as using the new live() method instead of bind().

Discussion

Why do event handlers get lost ?

JavaScript, as opposed to CSS, isn’t a declarative language. You don’t describe behaviors, and they get “automagically” applied.

JavaScript, like most other programming languages, is imperative. The developer specifies a sequence of actions to perform, and they get applied as the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required