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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)