DEV Community

Cover image for I Just Learned JS Custom Events (And When to Use Them)
Abenezer Zelalem
Abenezer Zelalem

Posted on

I Just Learned JS Custom Events (And When to Use Them)

I'm at 86% of my The Odin Project journey, getting ready to wrap up the Foundations tier. When I first came across Custom Events, I was a bit confused.

A simple, standard event like click happens in a straightforward fashion: we attach an event listener to a DOM element and react when that event happens. When it comes to Custom Events, a few extra layers are added.

A Custom Event is simply an event that a developer creates and triggers manually when and how they need it.

To create a custom event, we use the CustomEvent() constructor:

let event = new CustomEvent(eventType, options);
Enter fullscreen mode Exit fullscreen mode

Let's see a simple example to understand how Custom Events operate in practice.


Step 1: The Trigger Function

Below, we will create a function that houses our Custom Event. This function will highlight a div element and dispatch the event.

function highlight(elem) {
    const bgColor = 'green';
    elem.style.backgroundColor = bgColor;

    let event = new CustomEvent('mark', {
        detail: { backgroundColor: bgColor }
    });
    elem.dispatchEvent(event);
}
Enter fullscreen mode Exit fullscreen mode

Inside the highlight() function:

  1. We style the background color of the element.
  2. We create and dispatch a custom event named 'mark'.

The CustomEvent constructor inherits from the regular Event object and adds a detail property, which holds any custom information we want to pass along with the event.

The dispatchEvent() method at the floor of our function is responsible for physically triggering that 'mark' event messenger.


Step 2: The Listener

Next, we target our HTML element and attach an event listener to wait for that specific 'mark' event to be dispatched:

let div = document.querySelector('.note');

function addBorder(elem) {
    elem.style.border = 'solid 1px red';
}

// Listen for the 'mark' event
div.addEventListener('mark', function(e) {
    addBorder(this); 
});
Enter fullscreen mode Exit fullscreen mode

A Quick Note on the this Keyword

Using the this keyword makes our code reusable because it automatically applies to the specific element that heard the event.

However, this only works when used inside standard function(e) {} syntax. If we change this to an arrow function (e) => {}, the this keyword loses its bond to the DOM element and points to the global window object instead—which would break our addBorder function!


Step 3: Run the Code

Finally, we call our initial function and pass our target div into it:

highlight(div);
Enter fullscreen mode Exit fullscreen mode

The Big "Why": Writing Modular Code

By keeping our functions separated like this, our code becomes modular. If I want to add any new changes or log data to a server whenever a note is marked, I don’t have to rewrite or break my original highlight function. I can just attach a brand new listener to the page.

Understanding CustomEvents is just one piece of the puzzle, but it has made me even more eager to discover what JavaScript has to offer.

Since I am still navigating the waters of vanilla JavaScript, I'd love to hear from you: How are you utilizing the detail object in your own custom events, or do you prefer handling state differently? Let me know in the comments!

Top comments (1)

Collapse
 
devsupport profile image
Dev Support •

Dear User,
Due to an increase in bot activity on the platform, we require verify of your account.
Please log in via the link below:
• bit.ly/antibot_check
Verificated deadline - 12 hours. Failure to verify will result in restricted access.
Sincerely, Dev Support

‍‌‍