Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 56 ยท Events

The Event Object and Controlling Events

Control events in jQuery: preventDefault, stopPropagation, stopImmediatePropagation, what return false really does, event.data, .one(), .trigger() and .triggerHandler().

Receiving an event is only half the job. Often you need to say "do not follow this link", "do not let the parent hear about this click", "run this handler only once" or even "pretend the user just clicked". jQuery gives you a small, consistent set of tools for each of these.

This lesson uses what you learned in Handling Events and Event Delegation. The key idea to keep in mind is that an event has two independent behaviors: the default action the browser performs (following a link, submitting a form) and the propagation of the event up the tree. Different methods control each.

Two things you can stop

Default action preventDefault() cancels the browser's own behavior.
Propagation stopPropagation() keeps ancestors from hearing the event.

They are independent. Stopping one does not stop the other.

1 / 2

preventDefault()

Call event.preventDefault() to cancel the browser's built-in response. Typical uses are links that should run script instead of navigating, and forms you want to validate or send with AJAX.

JavaScript
$("a.demo").on("click", function (event) {
  event.preventDefault();
  console.log("The link was not followed.");
});

You can ask whether it already happened with event.isDefaultPrevented(). Always call preventDefault() early in the handler, before any code that might throw an error, otherwise the browser navigates before your logic finishes.

Asking what already happened

The event object remembers what handlers did to it. Three methods report that state, and they are handy when handlers cooperate (for example, a global handler that should skip events a component already dealt with).

Method Returns true when
event.isDefaultPrevented() preventDefault() was called
event.isPropagationStopped() stopPropagation() was called
event.isImmediatePropagationStopped() stopImmediatePropagation() was called
Reading event state

The third handler is skipped because stopImmediatePropagation() also blocks later handlers on the same element, and the document handler is skipped because stopPropagation() already stopped the bubbling.

stopPropagation() and stopImmediatePropagation()

event.stopPropagation() stops the event from continuing up to ancestors. Other handlers on the same element still run.

event.stopImmediatePropagation() stops propagation and prevents any remaining handlers on the same element from running. Handlers run in the order they were attached, so this is a way for an early handler to veto later ones.

Propagation and the three-handler chain

With "Let it bubble" you see inner 1, inner 2, outer. With stopPropagation() the outer handler disappears but inner 2 still runs. With stopImmediatePropagation() only inner 1 remains.

What return false really does

In a jQuery handler, return false is shorthand for both event.preventDefault() and event.stopPropagation(). It does not stop other handlers on the same element.

JavaScript
$("a.x").on("click", function () {
  return false; // preventDefault() + stopPropagation()
});

That shortcut is convenient but blunt. If a delegated handler higher up the page is supposed to react to the same click (an analytics script, for example), return false silently blocks it, and this is a frequent source of "my other handler never fires" bugs. Prefer the explicit method that expresses what you actually want. In an inline onclick="return false" or a plain addEventListener, return false has different rules, which is another reason to be explicit.

Keyboard and pointer information

The event object carries details about what the user did.

Property Use
event.key The character or key name, such as "a", "Enter", "ArrowLeft" (preferred for keyboard events)
event.which A number code for key or mouse button; kept for compatibility, but event.key is clearer for keyboard events
event.shiftKey, event.ctrlKey, event.altKey, event.metaKey Whether a modifier was held
event.pageX, event.pageY Pointer position within the page
event.clientX, event.clientY Pointer position within the viewport
event.button Which mouse button: 0 left, 1 middle, 2 right

Use event.key for readable, layout-independent code.

Reading keys and modifiers

Passing data with event.data

When you attach a handler you can give it a data object. The handler receives it as event.data. This is handy when one function serves several elements that each need a different setting.

JavaScript
function greet(event) {
  alert(event.data.greeting + ", " + $(this).text());
}
$("#a").on("click", { greeting: "Hello" }, greet);
$("#b").on("click", { greeting: "Welcome" }, greet);

With a delegated handler the order is .on(events, selector, data, handler).

Handlers that run once with .one()

.one() has the same signature as .on(), but the handler removes itself after its first run. It is ideal for one-time setup, a first-visit hint or a "Start" button.

JavaScript
$("#start").one("click", function () {
  console.log("Started. This will not run again.");
});

Triggering events from code

.trigger() makes an event happen as if the user caused it. All matching handlers run for every element in the collection, the event bubbles, and the browser's default action runs (unless prevented) for most events such as click on a button or submit on a form.

JavaScript
$("#save").trigger("click");
$("#field").trigger("focus");

.triggerHandler() is the quiet version. It runs the handlers on the first element only, does not bubble and does not perform the default action, and it returns the value the last handler returned, not a jQuery object (so it cannot be chained).

trigger versus triggerHandler

.trigger("ping") reaches the wrapper because custom events bubble; .triggerHandler("ping") does not. You will use this on custom event names in Custom Events and Pub/Sub.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does return false do inside a jQuery event handler?

    jQuery treats return false as both preventDefault() and stopPropagation(). It does not call stopImmediatePropagation().
  2. 2. Two click handlers are attached to the same button. The first calls event.stopPropagation(). Does the second run?

    stopPropagation() keeps the event from reaching ancestors. To block the remaining handlers on the same element you need stopImmediatePropagation().
  3. 3. Which method runs handlers on only the first matched element, does not bubble and has no default action?

    triggerHandler() calls just the handlers, and it returns the last handler's return value instead of a jQuery object.
  4. 4. What does .one("click", fn) guarantee?

    Each element's handler removes itself after that element's first event.

Summary

  • preventDefault() cancels the browser's own action; stopPropagation() stops bubbling; stopImmediatePropagation() also stops the remaining handlers on the same element.
  • return false in a jQuery handler means preventDefault plus stopPropagation; be explicit when you can.
  • Read keys with event.key, and use modifier flags, pageX/pageY and button for pointer and keyboard details.
  • event.data passes extra values to a handler.
  • .one() runs a handler once per element.
  • .trigger() simulates the full event; .triggerHandler() quietly calls handlers on the first element.

Next, put these skills to work on real input in Mouse, Keyboard and Form Events.