Home

1 minute read

Creating a Custom Event in Javascript

Tony Lea

Creating a Custom Event in Javascript

Using javascript events and listeners are very simple. If you've been programming in javascript you're probably already familiar with listening to click events like the following:

document.getElementById('my-button').addEventListener('click', function(){
    console.log('do something awesome!');
});

The code above will run when the my-button element is clicked, and this click event (among many others) are already made available for us to use. But, what if you wanted to create your own event? That's actually very simple as well.

Creating a Custom Event

In order to create a custom event we can do something like the following:

function create_custom_event(){
    
    var element = document.getElementById('my-button');
    
    element.classList.add('active')
    
    // Create a new custom event
    var event = new CustomEvent('madeActive');

    // Dispatch the event on the element
    element.dispatchEvent(event);
}

Above we have just created a custom event called madeActive, so now anywhere in our application we can now listen for this event and run some new functionality when this event has been fired.

Listening for a Custom Event

Listening to your custom event is going to look exactly like every other Event Listener in javascript. You will attach addEventListener to your element and specify the event you are listening for:

document.getElementById('my-button').addEventListener('madeActive', function(){
    console.log('Awesome, my own custom Event!');
});

Now, the code above will be run whenever the madeActive event (or your custom event) has been fired. 


Using custom events in your application can help you organize your code and make it more readable. It will also make it easier to maintain because you can fire events in one place and any place a listener is listening, it will run your desired functionality.

Cheers to custom events!