JavaScript Event Listeners
Have you ever visited a website and been in awe of the number of things you could do on the page? With the click of a button, you can express your interest in a post you ‘like’. With the tap of the keyboard, you can tell Mario to jump over an angry mushroom. With a hit of the ‘Submit’ key, you can post how passionately you feel about a particular topic. These all make websites and applications extremely dynamic and can provide a much more enjoyable experience for the user. But how do we, as developers, add these wonderful experiences to our applications for the user to interact with? Why, through Event Listeners, of course!
What is an Event Listener?
First off, we need to figure out what exactly an event is. An event can be defined as anything that a user does on our page. This includes things such as moving the mouse, pressing a key on the keyboard, clicking something on the page, and anything else that the user may do while perusing our beautiful applications. An event listener does just as the name suggests: it listens, or checks, for an event that has taken place and takes action based on the developer’s instructions. When a user clicks a ‘like’ button, for instance, we may have the button turn pink to indicate that the user has liked this post!
Syntax
Most commonly, event listeners are added to an element of the DOM (Document Object Model). We can add an event listener by using the .addEventListener() method. This method sets up the action that is to take place once the event is triggered on the page. It takes two arguments: the event type (a string) and a callback function that will execute in response to the event, often called the handler. Many times we’ll see the event handler be an anonymous or arrow function. The code when adding an event listener looks like this:
DOMElement.addEventListener(eventType, eventHandler)Common Type of Events
The Click Event
The click event is probably the most common and easily recognizable event in JavaScript. The click event is triggered when a user clicks on something on the page. This can be a ‘like’ button, an icon, or anything else that can be seen on our application. Let’s say we want to create a website where the user can click a button on the page and get alerted that the button has been clicked. We could use the following code:
button.addEventListener('click', function(){
alert('You clicked the button!')
})Now, every time our button is clicked, the user will see an alert that says “You clicked the button!” Notice how our callback function, or handler, here is an anonymous function. This is common when an event listener only has a few lines of code, but we should get into the habit of creating a separate event function for our longer handlers and passing that into our Event Listener function.
The Mouseover Event
The mouseover event is triggered when the user drags the mouse (or trackpad) over the target element. This event is often used to change the underlining or color of a link or to give the user more information about what they are hovering over. Say we want to tell our user what will happen if they click the link they have decided to hover over. We’d write the following code:
link.addEventListener('mouseover', function(){Get Kahlia Pinkins’s stories in your inbox
Join Medium for free to get updates from this writer.
alert('This link will take you to another page!');
})
Great! Now every time our user points to that link, they’ll be alerted that the link will take them to a separate page! You’re really getting the hang of this!
The Keydown Event
The keydown event is another event that you’ll run into fairly often as a JavaScript programmer. This event is triggered when a button on the keyboard is pressed. An example of this would be when a user is able to press any key to continue. If we want to be more specific with which keys we allow to trigger our event, for example, Mario jumps when the spacebar is hit, we have to do a few extra steps. The first thing we need to do is identify what event code is given when pressing the spacebar. Once we know this, we will know which code to look for when adding our listener. We can see this by logging our event to the console and seeing the properties that it contains:
window.addEventListener('keydown', event => console.log(event))Notice that we added our event listener to the window since the keydown event is linked to the keyboard rather than anything specific on the DOM. Also notice that we passed in event as our function’s argument. This is because the .addEventListener() method automatically passes in the event associated with the event type we put in as its first argument. When logging it to the console, we can see the event that is taking place and all of its properties. We see here from the logged event, the event key code for pressing the spacebar is 32. We now have enough information to create a listener for our keydown event where we only want the spacebar to trigger an action. Let’s say we want to alert our user once we press the spacebar. We could use the code:
window.addEventListener('keydown', function(event){
if(event.keyCode === 32){
alert('You pressed the spacebar!')
}
})As you can see, we added an if statement to ensure that our event triggers only when the spacebar is hit (the event with the key code 32). This extra step is necessary for both key down and key up (action upon letting go of a key) events if we want to be specific with our keys.
The Submit Event
The submit event is very special. This is an event where a form is submitted and usually, something is rendered to the page after submission. The unique thing about the submit event is its link to HTML forms. Because the submit event is always attached to an HTML form, its default behavior is to refresh the page whenever the submit button is clicked, bypassing the rest of the code we wrote in the event handler. Because of this, we need to counteract this default action so that our form can submit without interruption. We can do this by using a method called .preventDefault(). .preventDefault() will prevent the default behavior of the form and the page will not refresh upon submission. Therefore, if we want to alert the user that we have submitted our form, we can use the following code:
form.addEventListener('submit', function(event){
event.preventDefault();
alert('Your form has successfully been submitted!')
})Now, because we were able to prevent the page from refreshing, our submit event is successfully running!
Why You Should Love Event Listeners
Event Listeners are a JavaScript Developer’s best friend! Events are what connect your applications to your users. Without event listeners, our users wouldn’t be able to interact with our page in a meaningful way and would surely go and find a more interesting and interactive webpage to connect with. Get familiar with the concept of event listeners and add as many to your page as you can! I say, the more event listeners, the better! Happy Coding!




