DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

jQuery .trigger(): How to Create and Handle Custom Events

Attach a custom event handler with .on(), dispatch it with .trigger(), and choose .triggerHandler() when you need a non-bubbling event on only the first matched element.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To create a custom event in jQuery, attach a handler with .on(), then dispatch that event with .trigger(). You can pass dispatch-time data to the handler, let the event bubble to ancestors, or use .triggerHandler() when you want a narrower, non-bubbling call on only the first matched element.

How to create and trigger a custom event

A custom event is a named signal your code can use to tell other parts of an application that something happened. jQuery does not require a separate event declaration: register a handler for the event name, then trigger it on the element whose listeners should receive it.

  1. Select the element: create a jQuery collection for the element that will emit the event.
  2. Register a handler: call .on("item:added", handler) on that collection.
  3. Dispatch the event: call .trigger("item:added") on the relevant collection.

For example, a panel can announce that an item was added and include the item as data:

const $panel = $("#panel");

$panel.on("item:added", function (event, item) {
  console.log("Added:", item);
});

$panel.trigger("item:added", [{ id: 42, name: "Example" }]);

The handler receives the jQuery event object first, followed by any extra arguments supplied when triggering. In this example, item is the object passed in the one-member array. See the jQuery API documentation for .on() and .trigger().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

How to pass data to a handler

Use the second argument to .trigger() for information that becomes available when the event is dispatched. When that argument is an array, each array member becomes a separate handler argument after the event object:

$panel.on("item:added", function (event, item, source) {
  console.log(item.name, source);
});

$panel.trigger("item:added", [
  { id: 42, name: "Example" },
  "cart"
]);

Here, the handler arguments are event, item, and source. A single string or numeric extra argument can be passed without an array wrapper in jQuery 1.6.2 and later. For compatibility with older versions or when supplying multiple values, use an array.

Rank #2
Sale
JavaScript and jQuery: Interactive Front-End Web Development
  • JavaScript Jquery
  • Introduces core programming concepts in JavaScript and jQuery
  • Uses clear descriptions, inspiring examples, and easy-to-follow diagrams

Do not confuse this with the optional event data supplied to .on(). That data is attached when the handler is registered; extra parameters to .trigger() are provided at dispatch time. The .on() documentation describes event data, while the .trigger() documentation covers extra parameters.

What happens when a custom event is triggered?

.trigger() runs handlers for every element in the jQuery collection. Triggered events bubble up the DOM tree by default, so an ancestor with a matching handler can also observe the event. A handler can stop propagation when the event should not continue upward.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The event is synthetic: jQuery creates an event object and invokes applicable handlers, but the result is not identical to a naturally occurring event caused by a user’s physical interaction. The jQuery API documentation cautions that .trigger() does not perfectly replicate a naturally-occurring event. Use it to coordinate application code, not as proof that a user actually clicked, typed, or interacted with the browser.

.trigger() vs. .triggerHandler()

Choose based on how broadly the event should run and what result you need:

Behavior .trigger() .triggerHandler()
Matched elements Runs handlers for all elements in the collection. Runs handlers only on the first matched element.
Bubbling Bubbles through the DOM by default. Does not bubble.
Default action May cause the associated default behavior. Does not cause the default action.
Return value Returns the jQuery collection. Returns the last handler’s return value.

Use .triggerHandler() when you specifically need jQuery handlers on just the first element, without bubbling or a default action, and want the last handler’s return value. Consult the official .triggerHandler() documentation for details.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use namespaces to manage custom handlers

A namespace can label a handler so related listeners can be removed selectively. For example, item:added.widget identifies the event name item:added and the namespace widget:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$panel.on("item:added.widget", handleWidgetItemAdded);

// Remove handlers associated with the widget namespace
$panel.off(".widget");

Namespaces are handler-management labels, not hierarchical event types. They are useful when a component needs to clean up its own handlers without removing unrelated listeners. The .on() API documentation explains event names and namespaces.

When not to use .trigger()

If the goal is simply to run a particular function, call that function directly rather than using an event as an indirect function call. A shared function can be called by both the UI handler and other application code, while custom events are better suited to announcing that something happened to any interested listeners. The jQuery Learning Center recommends against using .trigger() simply to execute specific functions. For a broader introduction, see Introducing Custom Events.

Quick Recap

SaleBestseller No. 1
Web Design with HTML, CSS, JavaScript and jQuery Set
Web Design with HTML, CSS, JavaScript and jQuery Set
Brand: Wiley; Set of 2 Volumes
$35.05
SaleBestseller No. 2
JavaScript and jQuery: Interactive Front-End Web Development
JavaScript and jQuery: Interactive Front-End Web Development
JavaScript Jquery; Introduces core programming concepts in JavaScript and jQuery; Uses clear descriptions, inspiring examples, and easy-to-follow diagrams
$22.75

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.