DEV Community

Cover image for A Complete Guide To Custom Events In JavaScript
Mohit
Mohit

Posted on • Originally published at Medium

A Complete Guide To Custom Events In JavaScript

The DOMContentLoaded event, which is triggered at the moment when the browser is done loading and parsing HTML to the unload event, triggered just before the user leaves your site. Events are almost everywhere in a Web App. These events help in determining what just happened in an application & what the user’s state was specific at that time and more.

But the available JavaScript events are not adequate for describing the state of an application.

For example, when a user login fails and you want the parent component to know about the failure, there is no such login- failed event.
And to solve these issues we can surely create custom events in JavaScript for our applications.

We will cover:

  1. How to use & create custom events in JavaScript
  2. Using the CustomEvent constructor.
  3. Dispatching custom events.
  4. How Custom Events Work.
  5. Drag & Drop in JavaScript.
  6. Using Object Destructuring In JavaScript.

Prerequisites.

  1. HTML & CSS.
  2. JavaScrip (ES6).
  3. DOM & DOM Manipulation.

1. How to create custom events in JavaScript
There are certainly two ways to create custom events:

  1. Using the Event constructor.
  2. Using the CustomEvent constructor.

A custom event can be created using the event constructor, like this:

We created the event myevent, by passing the event name to the Event constructor. Event names are case sensitive so we named them as myEvent and MyEvent.

a). bubbles

The bubbles property specifies whether the event should be propagated upward to the parent element or not.
If we set this to true it will get dispatched in a child element and the parent element can listen to the event and perform an action based on that. That's the behavior of most DOM events and for custom events, it is set to false by default. In case we only want it to be dispatching a particular element we can stop the propagation of the event via event.stopPropagation().

b). cancelable

The name implies all of it, cancelable specifies whether the event should be cancelable.
Native DOM events are cancelable by default so we can call event.preventDeafult() on it which will prevent the default action of the event if the custom event had cancelable set to false, as calling the event.preventDeafult() will not perform any action.

c). composed

The composed property specifies whether the event should bubble across from the shadow DOM (created when using the web components)to the real DOM.
If the bubbles is set to false, the value of this property won’t matter as we are explicitly telling the event not to bubble upward. If you want to dispatch a custom event in a web component and listen to it on a parent element in the real DOM and then the composed property needs to be set to true.
But this method comes with a drawback as we cant send data across the listener, and in most applications, we would want to able to send data across from where the event is being dispatched to the listener. Ans to do this we can use the CustomEvent controller.

You can also send data using DOM events.

2. Using The CustomEvent constructor

A custom event can be created using the CustomEvent constructor like this:

creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor, the only difference is in the object passed as the second parameter to the constructor. While creating the Event constructor, we are limited by the fact that we cant pass data through the event to the listener. Any data that needs to be passed to the listener can be passed in the detail property which is created while initializing the event.

3. Dispatching Custom Events

After creating the events you need to dispatch them and events can be dispatched to any object that extends EvenTarget, and they include all HTML elements and the document, the window.

For Example:

To listen for a custom event, we add an event listener to the element you want to listen on. Just similar, we do in native DOM events.

4. How Custom Events Work

To understand how we use custom events in JavaScript applications we'll build a simple app that allows users to add a profile and automatically get a profile card.

The UI

Create a folder and name it anything you prefer and create an index.html file in the folder.
Add the following to the index.html :

This will be the markup for the page.

The page has two sections and the first section is a form that allows the user to the following:
Upload an image via drag & drop or by manual selection.

  1. Enter a name.
  2. Enter an occupation.

The data initialized from the form will be displayed in the section, which is the profile card. And the second section just contains some placeholder text and images, the data received from the form will overwrite the content placeholder data.

Then create the following style.css file:

And at the last create an index.js file so we can add functionality to the application.

5. Drag & Drop In JavaScript

We will add the functionality to upload images by drag and drop or by manual selection. For this add the following to the index.js file.

This allows us to listen on the events that are required to allow drag and drop operations (dragover, dragcenter & drop).

In the handleDragOver function, we are ensuring that the item being dragged is a file and setting the drop effect to copy, also the handleDragCenter performs a similar function that making sure that we are handling the dragging files. The actual work happens when the file is dropped and we handle that using handleDrop.

At first, we prevent the browser’s default action which to open a file before delivering it. We are also validating if that is an image and if it’s not we send an error message to let the user know we only accept image files. And if the validation passes we proceed to process the file in the handleFileUpload function which we will create next.

Now update the index.js file with the following:

We can simply add the event listener as you simply do and call the handleCardUpdate function when it is triggered.

Read My Full Post At: https://medium.com/javascript-in-plain-english/a-complete-guide-to-custom-events-in-javascript-4db599b49551

Top comments (0)