Tangential to the OP, but the concept that helped me unravel confusion with this feature is that the bound elements must be parents of the selected elements.
- Bound refers to what is left of the
.on
. - Selected refers to the 2nd argument of
.on()
.
Delegation does not work like .find(), selecting a subset of the bound elements. The selector only applies to strict child elements.
$("span.green").on("click", ...
is very different from
$("span").on("click", ".green", ...
In particular, to gain the advantages @N3dst4 hints at with "elements that are created in future" the bound element must be a permanent parent. Then the selected children can come and go.
EDIT
Checklist of why delegated .on
doesn't work
Tricky reasons why $('.bound').on('event', '.selected', some_function)
may not work:
- Bound element is not permanent. It was created after calling
.on()
- Selected element is not a proper child of a bound element. It's the same element.
- Selected element prevented bubbling of an event to the bound element by calling
.stopPropagation()
.
(Omitting less tricky reasons, such as a misspelled selector.)