JavaScript Events: A Beginner's Guide to Types of Events and Event Handlers

JavaScript events are a fundamental aspect of DOM Manipulation, serving as the driving force behind dynamic and interactive web applications. These events enable developers to manipulate the behaviour of web page elements in response to user actions, thereby fostering a more engaging user experience. Understanding JavaScript events is crucial for any developer seeking to build cutting-edge web applications.

In this article, we'll have a look at the following:

  • How JavaScript events work.

  • Event Handlers.

  • Passing an argument to event handlers.

  • Types of events.

  • Removing event listener from HTML elements.

Prerequisites

  • Web browser.

  • Code Editor.

  • Basic HTML and CSS knowledge.

  • Basic knowledge of the DOM.

How JavaScript Events Work

Imagine you're taking care of your friend's apartment, and they tell you only to open the door when someone knocks in a specific way. While going about your own business, you listen attentively for that particular knock. You hear various knocks from different people but don't open the door. Finally, you hear the expected knock and promptly open the door. Congratulations! You just acted as an event handler for a unique door-knocking event.

In JavaScript, events are simply actions in the browser, such as a user clicking on a button, submitting a form, scrolling a page, etc. When an event occurs, the attached event handler function invokes, which can modify webpage elements in response to user action. This only happens with an event listener that's connected to the element before the event and vice-versa.

Another way to look at it is that a JavaScript event is a signal generated by a particular DOM node in response to a user action. The generated signal is an indication that something has happened. Something like a click somewhere, the mouse moving, or the user triggering the fullscreen mode, amongst other important things that happen on a webpage.

Event Handlers

When an event signal is generated by a particular DOM node, the generated signal calls/invokes the event handler function, a block of instructions that get executed from top to bottom in response to an event. The nature of instructions would determine the nature of variables that get declared and accessed either locally or globally.

The .addEventListener() method is a built-in method in JavaScript that allows you to add an event listener to an HTML element. The method takes 2 compulsory arguments and 1 optional argument.

The first compulsory argument is a string that specifies the type of event that is being listened to. Examples of such variety of events include but are not limited to "click," "keydown," "keyup," "keypress," "mouseover," "mouseenter," "mouseleave," "DOMContentLoaded," "resize," etc.

The second compulsory argument is the event handler function, a callback function invoked to respond to an event.

The third argument, useCapture, is an optional boolean value determining the order in which event handlers are called. Event handlers either get called during the capture phase or the bubbling phase. This third argument is usually omitted and set to a default value of false. Explore JavaScript Event Propagation in-depth with this comprehensive blog post.

Passing an Argument to Event Handlers

Since an event handler is a function in JavaScript, an argument can be passed. Passing an argument into a handler function gives us access to the event object and its properties. We can access more information about the event through the object properties.

The snippet below shows how to pass an argument into an event handler function, assuming that we have a button element with an Id of btn-toggle in the DOM.

const button = document.getElementById("btn-toggle");
button.addEventListener("click", (e) => {
//e is the passed argument. e is a short form for event.
});

In the case of a click event, the event object gives us access to properties like the target and currentTarget, which tells us the element being clicked. It is crucial to note the subtle difference between an event target and an event currentTarget. An event target is an element where the event originated. In contrast, the event currentTarget is the element where the listener is attached.

Let's take a look at the codepen below for a better understanding.

Types of Events

There are several JavaScript events out there, but considering that our target readers are beginners, I would only talk about a few important events, including:

  1. Mouse events.

  2. Keyboard events.

  3. Form events.

  4. Window events.

Mouse Events

A mouse event occurs when a user interacts with the mouse on a webpage. Examples of mouse events include:

  • click

  • mouseover

  • mouseout

  • mousedown

  • mouseup

The click event is the most common type of mouse event in JavaScript. The codepen below shows how to attach a mouse event to an element.

Clicking on the Click Me to Toggle Text button causes the text to toggle between visible and hidden. The event is a button clicked by a user. The response to the event is the text's visibility toggle, handled by the instructions in the event handler.

Nothing happens after you click the Click Me for Fun button. That is because an event listener wasn't attached to the button element. Hence the event happens but with no response to the event.

Keyboard Events

A keyboard event occurs when a user interacts with the keyboard on a webpage. Before now, we've been attaching eventListener to specific elements. But in the case of a keyboard event, the event listener is attached to the entire document.

Examples of keyboard events include:

  • keydown

  • keyup

  • keypress

The keydown event is fired when a user presses down a key on the keyboard. Hence multiple fires can happen when pressed down for a long duration. The keyup event is fired when a key on the keyboard is pressed and released. In contrast, the keypress event gets fired during a keydown or keyup event.

The snippet below shows how to create a keydown keyboard event. The same approach can be used for keyup and keypress events.

document.addEventListener("keydown", (e) => {
// the console below provides information about the keyboard event and the key being pressed down.
  console.log(e, e.key);
// executing commands when a particular key is pressed down
if(e.key === "Enter"){
console.log("Hurray, Enter key pressed!");
// PS: always console the key property of target key to confirm spelling, if in initial caps or lowercase. 
} 
});

Form Events

A form event occurs when a user interacts with a form element on the webpage. Examples of form elements include text input fields, textarea, radio, checkboxes, date picker, submit button, etc.

Examples of form events include:

  • focus

  • submit

  • change

  • reset

  • blur

The snippet below shows how to attach a focus event to an input element, assuming that we have an input element with an Id of name-input in the DOM.

const input = document.getElementById("name-input");
input.addEventListener("focus", (e) => {
// do something!
});
// The focus event gets fired when the user focuses their mouse cursor in the input field.

Window Events

Changes to the browser's window fire window events. You can use the addEventListener() method on the document or window object to listen for a window event.

Examples of window events include, but are not limited to:

  • load

  • resize

  • scroll

  • DOMContentLoaded

The snippet below shows how to create a DOMContentLoaded event.

// DOMContentLoaded event fires when the initial HTML document has been completely loaded, but external resources like images and stylesheets may not have finished loading yet.
window.addEventListener("DOMContentLoaded", () => {
// do something!
});

Removing Event Listener from HTML Elements

Without attaching an event listener to elements, it wouldn't be possible to respond to user actions dynamically. But one of the Cons of not correctly managing an event listener is that it results in performance issues.

To successfully remove an event listener from an HTML element, the same event type and handler function must be passed into the .removeEventListener() method as arguments.

Let us have a look at how we can remove event listeners from an HTML element in the codepen below.

Conclusion

Without a doubt, JavaScript Events is a must-know for JavaScript and Front-End Developers. Without events, an element wouldn't know how to respond dynamically to user action on the webpage. These dynamic interactions are necessary for webpages to be super interactive and exciting.

Like every other good thing, a sacrifice will always be made. In the case of JavaScript events, having too many uncontrolled event listeners across the codebase can result in page performance issues. This issue can be fixed by removing an event listener after the first click or with the setTimeout function.

I left off a few things, like how to use the setTimeout function to remove event listeners. This is because the article is targeted at beginners, hence the need to keep things simple. You can look up MDN to read more on JavaScript Events.

That's all, folks! I hope this was helpful. Please do well to leave some feedback and share the article with friends.