Read more

jQuery: How to attach an event handler only once

Arne Hartherz
November 06, 2015Software engineer at makandra GmbH

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

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2015-11-06 12:14)