0Pricing
jQuery Academy · Lesson

Creating and Triggering Custom Events

Design and implement custom events using .trigger() and .on() to decouple components, create cleaner code, and enable flexible communication between different parts of your application.

Creating and Triggering Custom Events is a free jQuery Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the jQuery Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Intro to Custom Events

Welcome! In this lesson, you'll learn how to create and manage your own custom events in jQuery. This is a powerful way to make your code more organized and flexible.

Think of custom events as special messages that different parts of your web application can send and receive. This helps them communicate without being directly linked.

Why Use Custom Events?

Why bother with custom events? They help solve a common problem: tight coupling. When components are tightly coupled, changing one part of your code might break another.

  • Decoupling: Components don't need to know about each other's internal workings.
  • Cleaner Code: Logic related to a specific action is centralized.
  • Flexibility: Easily add or remove listeners without altering the 'sender'.

The .trigger() Method

To 'send' or 'fire' a custom event, we use jQuery's .trigger() method. You call it on a jQuery object (an element or document) and pass the event name as a string.

The event name can be anything you choose, like 'dataLoaded' or 'itemAdded'.

Triggering an Event Demo

Let's see .trigger() in action. We'll fire a custom event called 'myCustomEvent' on a button when it's clicked. Nothing will happen yet, because no one is listening!

<!-- HTML assumed to be present -->
<button id="triggerButton">Trigger Event</button>

<script>
$(document).ready(function() {
  $('#triggerButton').on('click', function() {
    // Fire our custom event on the button itself
    $(this).trigger('myCustomEvent');
    console.log('myCustomEvent triggered!');
  });
});
</script>

Listening with .on()

To 'receive' or 'listen' for a custom event, we use the familiar .on() method. Just like with built-in events (like 'click'), you specify the event name and a function to run when it fires.

You can listen on the same element that triggered the event, or on a parent element, or even the document itself for global events.

Trigger & Listen Example

Now, let's put .trigger() and .on() together. Click the button, and you'll see the message appear, showing that our custom event was both triggered and heard!

<!-- HTML assumed to be present -->
<button id="myButton">Click Me</button>
<p id="statusMessage">Status: Waiting...</p>

<script>
$(document).ready(function() {
  // 1. Listen for 'buttonClicked' on the button
  $('#myButton').on('buttonClicked', function() {
    $('#statusMessage').text('Status: Custom event received!');
  });

  // 2. When the button is clicked, trigger 'buttonClicked'
  $('#myButton').on('click', function() {
    $(this).trigger('buttonClicked');
  });
});
</script>

Passing Data with Events

Custom events are even more useful when you can pass data along with them. You can send extra arguments to .trigger() after the event name. These arguments will be passed to your event handler function.

  • The first argument in the handler is always the event object.
  • Subsequent arguments are the data you passed with .trigger().

Custom Event Data Demo

Here, we trigger a 'dataReady' event and pass a string and an object. The listener receives this data and displays it. This is how components share information!

<!-- HTML assumed to be present -->
<button id="loadData">Load Data</button>
<p id="output"></p>

<script>
$(document).ready(function() {
  // Listen for 'dataReady' and extract the passed data
  $(document).on('dataReady', function(event, message, details) {
    const outputText = `Message: ${message}<br>Details: ${details.status} for ${details.item}`; 
    $('#output').html(outputText);
  });

  // When button clicked, trigger 'dataReady' with data
  $('#loadData').on('click', function() {
    const msg = 'Data successfully loaded!';
    const data = { status: 'complete', item: 'report' };
    $(document).trigger('dataReady', [msg, data]);
    console.log('Data event triggered!');
  });
});
</script>

Decoupling for Better Apps

Using custom events for communication helps in building more modular and maintainable applications. Imagine a 'shopping cart' component and a 'product display' component.

  • When a product is added, the 'product display' triggers 'productAdded'.
  • The 'shopping cart' component listens for 'productAdded' and updates itself.

Neither component needs to know about the other's internal methods, only the event contract.

Check Your Understanding

Which of the following statements correctly describe the benefits or usage of custom events with .trigger() and .on()?

Recap: Custom Events

Great job! You've learned how to create and manage custom events in jQuery. Here's a quick summary:

  • What: Custom events are user-defined messages for application components.
  • Why: They promote decoupling, leading to cleaner, more flexible code.
  • How: Use .trigger('eventName', [data]) to fire an event.
  • How: Use .on('eventName', function(event, data) { ... }) to listen for an event.

Mastering custom events is a key step towards building robust and scalable jQuery applications!

Frequently asked questions

Is the “Creating and Triggering Custom Events” lesson free?

Yes — the full text of “Creating and Triggering Custom Events” is free to read here on the web, and the jQuery Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the jQuery Academy course, upgrade to CoddyKit PRO.

What will I learn in “Creating and Triggering Custom Events”?

Design and implement custom events using .trigger() and .on() to decouple components, create cleaner code, and enable flexible communication between different parts of your application. You practise jQuery Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start jQuery Academy?

No prior experience is required. jQuery Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Creating and Triggering Custom Events” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this jQuery Academy lesson?

Yes. Every jQuery Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Implementing Robust Event Delegation
  2. Stopping Event Propagation
  3. Creating and Triggering Custom Events
← Back to jQuery Academy