jQuery: How to attach an event handler only once

Updated . Posted . Visible to the public.

With "attaching an event handler once" you possibly mean one of these two things:

Register a function for an event, and discard it once that event has happened

Use one instead of on.

$(element).one('eventName', function() { ... });

It has the same API has on.

When code is run multiple times that registers a function for an event, do that only once

With jQuery, you can de-register callbacks. You can use that to achieve registering a function only once.

function myAction() { ... }; // defined somewhere globally or in your complex closure

// Then, inside your code that may be run more than once:
$(element).off('eventName', myAction).on('eventName', myAction);

That will de-register any existing callbacks for that event and that function, and then register it again. Not pretty, but works and is fast enough.

Please note: For this to work your code must point to the correct function when deregistering. An "anonymous" function that does the same inside its body (like "$(window).off('resize', function() { ... }).on('resize', function() { ... }") is different each time.

Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2015-11-06 11:14)