JavaScript Event Listeners for Every Newbie Developer

This tutorial demonstrates important JavaScript events like keydown, click, load, and more. Includes code and examples on how to use the events.

Being a web developer means you’re an Avatar in your little world. But you aren’t bending earth, fire, air, or water. What you are doing is: “bending” different coding languages. One such language is JavaScript. And just as we’ve pointed out in one of our previous JavaScript tutorials, you aren’t a complete web developer if you haven’t mastered JavaScript. It’s a different world! So, are you indeed a newbie or a web designer who finally understands and appreciate the value of this language? Either way, I’ve got something I’d like to share with you.

In this tutorial, we’ll lead you through a perfect beginner’s path. First, we’ll explain a couple of valuable concepts. Then, with it, you’ll be able to implement, correctly, one of JavaScript’s essential elements: The Event Listener.

JavaScript Event Listeners – The Introduction

So, what, exactly are Event Listeners? They are among the most common JavaScript features in web development. In this space (the web development world), JavaScript code lets you add interactive functionalities to different HTML elements by… you guessed it – listening to different events that often take place on web pages, including users pressing a key, clicking a button, or when an element is loading. 

An event is a crucial part of the JavaScript language, and this code defines how a web page would respond when an event occurs. While some events are browser generated, some are also generated by the platform’s users. More than just code, however, listeners are functions that sniff for events, waiting for them (these events) to occur.

What is the addEventListener Syntax?

.addEventListener(event, listener, useCapture);

What are the addEventListener parameters?

  • Event – The addEventListener event parameter includes any valid JavaScript event. In this case, the events are used without the “on” prefix. For instance, you could use “mousedown” rather than “onmousedown.” This is the prefix that we refer to.
  • Listener – The addEventListener listener parameter is a handler function that responds to the event.
  • useCapture – The addEventListener useCapture parameter is optional. It helps control event propagation. Thus, the “true” term denotes capturing phase in a Boolean value while “false” denotes the bubbling phase.

The addEventListener takes the event to look out for and a second argument to be sourced whenever the user or API triggers the event. A different number of events are added to an element without overwriting the existing handlers. 

When different events occur, we’ll send information to a server to execute code from the backend or process the data in the browser like using Local Storage.

Below we have some of the most used JavaScript events.

Note: The addEventListerner function accepts both an object and a function with a handleEvent() property function. This is due to the fact that there’s a need for compatibility with legacy content.

What are commonly used JavaScript events?

  • keydown
  • click
  • load
  • touchstart
  • mouseover

Check out the Event Reference guide on this Developer Mozilla page for more on DOM events. Once you’re done reading this, you’ll find out more about the crucial part of this JavaScript structure.

What are the different event phases?

There are two different event phases. These are:

  • Capture
  • Bubble

Whether trickling down or bubbling up, it is referred to as propagation when an event goes through the DOM. In this instance, the event propagates via the DOM tree. 

Reiteratively, these events happen in two different phases, and these are the bubbling phase as well as the capturing phase.

In the capture phase, also known as the trickling phase, the event in question trickles down to the element that triggered the event. It also begins from the root level element and the handler, and next, it propagates down to the element. Meanwhile, the capture phase is complete only when the event reaches the “target.” 

On the other hand, the event bubbles up to the DOM tree with the bubble phase. The innermost handler first captures this event, and it then propagates up to the higher spectrum of the DOM tree, further up to the DOM’s parents, and finally, to its (the DOM’s) root.

Example 1

JavaScript Click Event Listener
JavaScript Click Event Listener

Here’s a MouseOver and MouseOut Event example using an HTML id attribute.

HTML

<button id="clickIt">Click here</button>
<p id="hoverPara">Hover over this Text !</p>
<b id="effect"></b>

The JavaScript gets the button by the ID of clickIt and registers a click event listener. Addionally, the script gets a paragraph element with the ID of hoverPara and adds two event listeners, the mouseover and the mouseout. All these event listeners update the text of the bold element with the name of the event that is triggered.

JavaScript

const x = document.getElementById("clickIt");
const y = document.getElementById("hoverPara");

x.addEventListener("click", RespondClick);
y.addEventListener("mouseover", RespondMouseOver);
y.addEventListener("mouseout", RespondMouseOut);

function RespondMouseOver() {
  document.getElementById("effect").innerHTML += "MouseOver Event" + "<br>";
}

function RespondMouseOut() {
  document.getElementById("effect").innerHTML += "MouseOut Event" + "<br>";
}

function RespondClick() {
  document.getElementById("effect").innerHTML += "Click Event" + "<br>";
}

Here’s the complete code on codepen.io

Example 2

JavaScript onClick inline Event
JavaScript onClick inline Event

Tweak these lines of code

HTML

<p>Click this button</p>
<form>
  <input type="button" onclick="sayHello()" value="Say Hi" />
</form>

JavaScript

function sayHello() {
  alert("Hello World")
}

You can edit this example on codepen.io

Example 3

JavaScript mouseover and mouseout Events
JavaScript mouseover and mouseout Events

Here is another onmouseover and onmouseout example to play with

HTML

<div class="super-container">
  <div class="container">
    <p>Hover your mouse on the division:</p>
    <div onmouseover="over()" onmouseout="out()">
      <i>This is what you have in the in the division</i><br><br>
      <div>
        <b id="events"></b>
      </div>
    </div>
  </div>
</div>

JavaScript

function over() {
  document.getElementById("events").innerHTML = "Mouse Over";
}
function out() {
  document.getElementById("events").innerHTML = "Mouse Out";
}

The mouseout and mouseover event example can be edited on codepen.io.

Example 4

JavaScript resize Event
JavaScript resize Event

Triggering the resize event handler

HTML

<h2>AppCode JavaScript Tutorial</h2>
<p>Using the addEventListener() method</p>
<p>Resize your browser to trigger the "resize" event handler.</p>
<p id="demo"></p>

JavaScript

window.addEventListener("resize", function(){
  document.getElementById("demo").innerHTML = Math.random();
});

Find the resize event example on codepen.io.

Frequently Asked Questions

How do I listen to a JavaScript event?

Answer: When listening to a Javascript event, you can use a JavaScript event Listener. There are two ways to add a JavaScript event listener. You can use the addEventListener function or use HTML inline events. Which, when triggered, will execute a defined role or action. 

Recommended Articles

Other Articles