How do I attach events to elements created in the future in jQuery, only once?
I understand that .live() works in attaching events for elements created in the future, but will attach events multiple times like .bind() does. But I need to attach the event only once.
EXAMPLE:
For my case
http://jsfiddle.net/ppTqp/1/ -> Should alert “Live from test” only once. With .live method it alerts twice.
Update:
Apparently you want that an event handler is only bound once when you make several calls to
live,delegateoron.In this case you’d have to unbind the event handler first. You can use namespaces to only unbind the specific event handler:
In case of
live, you have to calldie:I assume the event handler is bound to several elements. Due to the nature of
live,delegateoron(for that matter), you cannot just “unbind” the event handler when it was executed for one element, as it won’t be fired for any other element anymore. Instead, uou have to keep track for which element it was fired.Example:
The other solution would be to use
.one()and bind the event handler whenever you create new elements.Regarding your terminology:
You cannot attach events, but event handlers.
binddoes not attach events or event handlers multiple times, just once, but once it is bound, it will always fire for a certain event. If you want to an event handler to be called only once, you have to unbind it after it was called.