Menu Home

addEventListener()

Hey everyone! It’s time for another exciting edition of Boring JavaScript. Today we cover the addEventListener() method for DOM elements.

Listen to the Band!

addEventListener() let’s your code capture events that may occur either from:

  1. Interaction with the user of the app (click, change, focus, etc.)
  2. Interaction with other applications (start/end streams, video progressions, etc.)
  3. Interactions you generate yourself (custom events)

Once those events occur, JavaScript will then execute a function you pass to the addEventListener() method, using the Event object generated by the process that threw the event as the argument to your listener.

Is My Phone Ringing?

Let’s take a look at one of the most common events – the ‘click’ event.

Here is our HTML:

<body>
    <form id="userForm" method="POST" action="https://myserver.com/process">
        <label>Enter your name: <input type="text" id="username" /></label>
        <p><button type="button" id="submitForm">Submit</button</p>
        <p id="errorMessage">Your username must be at least eight characters in length. Try again.</p>
    </form>
</body>

Our goal here is to perform some sort of client-side validation on the username before submitting the form. We can do that by capturing the ‘click’ event on the Submit button, validating the username, then either display the error message or submit the form.

And here is our JavaScript:

const usernameDom = document.getElementById('username');
const userFormDom = document.getElementById('userForm');
const submitFormDom = document.getElementById('submitForm');
const errorMessageDom = document.getElementById('errorMessage');

submitFormDom.addEventListener('click', processSubmit);
usernameDom.focus();

function processSubmit(event) {
    errorMessageDom.classList.remove('show');
    const username = usernameDom.value;
    // here, you will check for all validations for the username you wish.
    if (username.length < 8) {
        errorMessageDom.classList.add('show');
        usernameDom.focus();
    } else {
        // all good! Submit the form
        userFormDom.submit();
    }
}

Line 6 is what we want to concentrate on. Here is it again:

submitFormDom.addEventListener('click', processSubmit);

Notice first that the ‘addEventListener’ method is on the DOM element retrieved from the ‘document.getElementById()’ method earlier. More that just DOM elements can throw events, though. You will need to check documentation on what can throw which events.

Second, let’s look at the two arguments:

  1. ‘click’ – This is the event itself. Represented by a string, it tells JavaScript what kind of event to listen for. I found about 385 events on the Mozilla Development Network pages. There’s probably more than that.
  2. processSubmit – This is the function that is to be executed once the event occurs. You will need to define this function somewhere in your code.

Speaking of the function, what’s the argument passed to it? It will be the Event object thrown by the eventing process. Actually, it is a super class of the Event object. For example, in our code above, the object thrown will be a MouseEvent (with the ‘type’ property being ‘click’). There are about 53 different super sets of the Event object, according to the Mozilla Developer network.

Customizing Your Work

There is one of the 53 Event super sets to which I want to draw your attention. That is the CustomEvent object. Using that your can create your own names of events and pass custom data to that event. And it’s real simple to use. Let’s take a look:

const myEvent = new CustomEvent('myEventName', { detail: someData });
document.dispatchEvent(myEvent);

// somewhere else in your application
document.addEventListener('myEventName', processCustomEvent);

function processCustomEvent(event) {
    console.log(`My detail data from the event is ${event.detail}`);
}

Notice the connection between Line 1 and Line 5. When you create a CustomEvent, you get to define your own event name. You can then use that event name with any event listener attached to any object. In the example above, we use the global ‘document’ object – but it could be anything in which an addEventListener() method is available.

And the ‘detail’ part? That’s custom data you can pass to the event. The data you pass can be any valid JavaScript object.

The Video

Here is the video we produced that shows the how all of the above works. Make sure you subscribe to our YouTube channel!

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: