Andi Smith

Technical Leader Product Engineer AI Consultant

jQuery On and Off Namespacing

  • By Andi Smith
  • 2 minute read

Quite a while ago, I wrote an article about jQuery .on() and off() - an improved way of attaching events in jQuery - and still the best way to attach events to DOM elements in jQuery.

Being able to apply and remove events with on() and off() is great, but sometimes there is a requirement to either trigger or remove a subset of events that have been added to an element. For example:

$(".item").on("click", doThisCoolThing);
$(".item").on("click", doThisOtherCoolThing);

$(".item").trigger("click"); // both functions are triggered
$(".item").off("click"); // both functions are removed.

Using event namespacing we can assign names to event handlers when we create them, and then use them later on to target specific functionality when we call trigger() or off(). The name you choose for your event namespace should be relevant for the functionality you are calling. For example:

$(".item").on("click.navigate", doThisCoolThing);
$(".item").on("click.notify", doThisOtherCoolThing);

// only the function assigned to the namespace navigate would be triggered.
$(".item").trigger("click.navigate");
// only the function assigned to the namespace notify would be removed.
$(".item").off("click.notify");

It's also possible to use multiple namespaces, like so:

$('.item').on('click.navigate.notify', doThisCoolThing);

// trigger the click event
$('.item').trigger('click.navigate');
function.
// remove the click event.
$('.item').off('click.notify');

Namespacing events in jQuery has been available for some time and isn't limited to just on() and off(). It also works with .bind() and .unbind() too.

Andi Smith

By Andi Smith

Andi Smith is a passionate technical leader who excels at building and scaling high-performing product engineering teams with a focus on business value. He has successfully helped businesses of all sizes from start up, scale up to enterprise build value-driven solutions.

More Blog Posts

  • Lessons from Startup Life

    Some things I learnt during my time working as tech employee #1 at a startup.

  • Inkscape 101

    I've been playing around with Inkscape for the first time this weekend. It's been fun and I've managed to get some good results really quickly. Here's my 101 intro to Inkscape! From one beginner to another beginner!

  • Intro to SOC 2 for CTOs

    Congratulations! You've reached the point in your business where you are mature enough to start thinking about cybersecurity and security compliance, but there's a lot of new information to get your head around.

  • Keeping SaaS Costs Down

    It's very easy to fall in to the trap of tool sprawl and escalating costs - particularly in the high speed world of startups. Let's take a look at some techniques we can use to keep a handle on it.