Logo
5 May 2014 | 1 min. (184 words)

Namespacing jQuery event handlers

If we are to attach 2 or more event handlers to an element these will become stacked and run linear in the order they were attached.

For example:

$(".foo").on("click", function(e){
    console.log("bar");
});

$(".foo").on("click", function(e){
    console.log("baz");
});

If .foo is then clicked, the browser console will log:

"bar"
"baz"

If we wish to remove these event handlers we can call:

$(".foo").off("click");

Simple.

However, what if we wish to only remove 1 of these event handlers and retain the other? This is where jQuery event namespacing comes in handy.

When adding the event handlers we can include a namespace name which will act as a reference when removing the event:

$(".foo").on("click.barevent", function(e){
    console.log("bar");
});

$(".foo").on("click.bazevent", function(e){
    console.log("baz");
});

Here click has been changed to click.xxxx where xxxx is the name of the namespace for this particular event handler.

With this in place we can remove 1 of the event handlers by referencing it’s namespace when calling .off().

For example if we wish to remove only the “bar” console log, we can call:

$(".foo").off("click.barevent");

Therefore if .foo is then clicked, the browser console will only log:

"baz"
javascript event-handlers jQuery namespace
Twitter Facebook

Create a flashing tab notification page title

Learn how to create flashing page title, or use/fork the existing version…

Default negative variables to zero in javascript

…

Related Links

  • LinkedIn
  • Twitter: @curtcode
  • Stack Overflow
  • GitHub: @curtiscde

Stack Exchange

profile for Curtis on Stack Exchange, a network of free, community-driven Q&A sites
Follow @curtiscde

Recent Posts

  • My terminal setup and commands I use on a daily basis when working with GitHub
  • Displaying latest posts on your GitHub profile
  • Using Codecov within a monorepo
  • Displaying Strava stats using webhooks & GitHub Actions
  • Filtering duplicate data points on Chart.js
Theme Bleak by zutrinken Published with Hugo
Menu