Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 56 ยท Events

Handling Events

Learn how to attach and remove jQuery event handlers with .on() and .off(), read the event object, tell this from event.target, and use namespaces.

A web page that never reacts to anything is just a document. Events are how pages come alive: a click, a key press, a form field changing, the window resizing. In jQuery you describe the reaction once, "when this happens to these elements, run this function", and the library takes care of the browser differences for you.

This lesson covers the core tools: .on() to attach a handler, .off() to remove it, the event object that every handler receives, the three easily confused ways to name "the element involved", and namespaces that let you remove only the handlers you added. You should already be comfortable with selecting elements and the document ready event.

The life of a handler

Attach .on("click", fn) registers it.
Run The browser calls fn with an event object.
Detach .off("click", fn) removes it.
1 / 2

Attaching a handler with .on()

The basic form is .on(eventName, handler). The handler is a function that jQuery calls every time the event fires on any element in the collection. Because of implicit iteration, one call attaches the handler to every matched element.

JavaScript
$("button.save").on("click", function () {
  console.log("Saving...");
});

Inside the handler, this is the DOM element that the handler is attached to. Wrap it with $(this) to get jQuery methods back.

Your first handlers

One call, three buttons. Each click runs the same function, and this points at whichever button was clicked.

Shorthand methods

jQuery also has a method named after many events: .click(), .submit(), .keydown(), .focus() and so on. With a function argument they are shortcuts for .on().

JavaScript
$("#save").click(function () { /* same as .on("click", ...) */ });

With no argument they trigger the event instead, which is covered in Controlling Events. Prefer .on() in new code. It is the one method that handles everything (delegation, namespaces, several events), and the shorthands for load, unload and error were removed in jQuery 3, as the jQuery 3 changes lesson explains.

The event object

jQuery passes one argument to every handler: an event object. It wraps the browser's native event and gives you the same properties everywhere.

Property Meaning
event.type The event name, such as "click"
event.target The element that actually triggered the event
event.currentTarget The element the running handler is attached to
event.timeStamp When the event happened, in milliseconds
event.pageX, event.pageY Pointer position relative to the page
event.originalEvent The native browser event, for anything jQuery does not copy

You can name the parameter anything. By convention it is event, e or evt.

this, event.target and event.currentTarget

These three cause more confusion than any other part of events. Events bubble: a click on a <span> inside a <button> fires on the span first, then on the button, then upward. A handler on the button runs during that trip.

  • event.target is where the event started: the span.
  • event.currentTarget is where the handler lives: the button.
  • this is the same node as event.currentTarget in a normal function.
Target versus currentTarget

Click the plain text and the target is div. Click the red word and the target becomes b, while currentTarget stays div#card.

An arrow function does not get its own this. In .on("click", () => { $(this) ... }) the this is the surrounding scope, not the clicked element. Use a regular function, or write $(event.currentTarget).

Several events and several handlers

Pass a space-separated list to share one handler between events, or an object to give each event its own.

JavaScript
$("#field").on("focus blur", function (event) {
  $(this).toggleClass("active", event.type === "focus");
});

$("#field").on({
  mouseenter: function () { $(this).addClass("hot"); },
  mouseleave: function () { $(this).removeClass("hot"); }
});

You can also attach several handlers for the same event on the same element. They run in the order they were added.

Removing handlers with .off()

Call .off() to take handlers away. Three levels of precision are available:

JavaScript
$("#btn").off("click", greet); // only this function
$("#btn").off("click");        // every click handler
$("#btn").off();               // every handler of every event

To remove a specific function you need a reference to it, so a named function (or one stored in a variable) is required. An anonymous function passed to .on() can never be matched later.

Namespaces

A namespace is a label you add after a dot. It lets you remove your own handlers without touching anyone else's, which matters in pages shared between widgets and plugins.

JavaScript
$("#panel").on("click.tooltip", showTip);
$("#panel").on("click.analytics", track);

$("#panel").off(".tooltip"); // removes only the tooltip handlers

.off(".tooltip") removes every event type carrying that namespace. A good plugin uses one namespace for everything it binds and tears itself down with a single .off().

Adding and removing handlers with namespaces

Attach both, click the box to see both run, remove A and click again: only B remains. Each "Add" button calls .off() first so pressing it twice never stacks duplicate handlers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a click handler written as a normal function, what is this?

    this is the raw DOM element the handler is attached to (the same node as event.currentTarget). Wrap it with $(this) to use jQuery methods.
  2. 2. A click lands on a <span> inside a <button> that has the click handler. What is event.currentTarget?

    currentTarget is always the element the handler is bound to, here the button. event.target would be the span.
  3. 3. Which call removes only the handlers added with .on("click.menu", fn)?

    A namespace selects just the handlers that carry it. Plain .off("click") would also remove other people's click handlers.
  4. 4. Why can an anonymous function passed to .on() not be removed with .off("click", fn)?

    off() matches by function identity, so you need to keep a reference. Otherwise use a namespace or remove all handlers of that event.

Summary

  • .on(event, handler) attaches a handler to every element in the collection; .off() removes handlers at three levels of precision.
  • Handlers receive jQuery's normalized event object; event.originalEvent is the native one.
  • event.target is where the event began, event.currentTarget (and this in normal functions) is where the handler is bound.
  • Arrow functions do not receive the element as this.
  • Use a space-separated list or an object to handle several events at once.
  • Namespaces such as click.menu let you clean up exactly what you added.

Next, make one handler serve many elements, including ones that do not exist yet, in Event Delegation.