With JQuery, is it possible to add an event listener to any element that currently, or will in the future, have a particular class?
I’m working on a project that makes heavy use of contentEditable, so the DOM is changing, and elements can have classes added and removed as a result of user input.
I would like to be able to say “elements of class X should do Y when clicked”, but if I understand correctly, $(“.X”).click(Y) will only add the event listener to elements that currently have class X.
Furthermore, if an element is no-longer part of class X, then it will still have the click event listener.
How can I do this?
Yep. What you’re talking about is called event delegation. Here’s an example:
In your case,
#containerwould be an element that is known to exist on page load which will contain the child elements you care about (either now or in the future). This approach takes advantage of event bubbling in the DOM.As another poster mentioned, the live method will also work — but it has been deprecated in jQuery 1.7, and is generally not as performant as using more selective delegation (such as the example above).