This was something that confused me for a while when I started JQuery – binding. You add a new html element and want to bind to a click event for example on that element. Sounds straightforward.
We have 2 divs, the first being static and the second being a placeholder that we will dynamically add more html elements to.
1 2 |
|
We add our elements using JQuery like this
1 2 3 4 |
|
When we browse to the page, as expected, we get the 2 divs.
Now we can add the click events:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
But the second click event does not work. Why? Well the answer is that the ClickMeToo
element does not exist when the JQuery does it’s binding and the new div we added is left out in the cold.
To resolve this, all we need to do is to amend the code $(‘#ClickMeToo’).click(function () { to the following:
1 2 3 |
|
The live
method tells JQuery to bind for all existing and future matches to the selector.
EDIT: the live
binding is now deprecated – use on
instead!