How to handle DOM events using JavaScript

Key takeaways:

  • Events in the DOM represent user actions or occurrences in the browser. They allow us to interact with and manipulate the DOM by responding to these actions, making applications more engaging and responsive.

  • Event listeners are functions that wait for specific events to happen on HTML elements. They’re added using methods like addEventListener().

  • To stop an event listener from responding, we can use removeEventListener(). This is useful when a specific event should only trigger a response once or under certain conditions.

  • We can manage complex event interactions efficiently. Using stopPropagation() can prevent further propagation, offering finer control over event behavior.

JavaScript event handling is a fundamental aspect of web development that allows us to create dynamic and interactive web pages. By reacting to user interactions using DOM (Document Object Model) events like clicks, typing, scrolling, and hovering—we can build dynamic applications that respond to users’ needs in real time. Let’s learn how to handle DOM events using JavaScript to create responsive, engaging interfaces.

What are DOM events?

The DOM is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. Events are user actions or occurrences that happen in the browser, such as clicking a button, moving the mouse, or pressing a key. It is a way to interact with the DOM by responding to user actions or other occurrences. Each event has a specific behavior and by handling these events, we can respond to user interactions and build engaging web applications.

Basics of JavaScript event handling

In JavaScript, event handling involves two key components: event listeners and event objects.

  1. Event listeners: Event listeners are functions that “listen” for specific events to occur on HTML elements. They are attached to elements using methods like addEventListener(). Let’s look at an example:

const button = document.querySelector('#myButton');
button.addEventListener('click', function() {
// Code to execute when the button is clicked
});

In the above code example, a click event listener is added to a button element identified by the ID myButton. The function specified as the second argument is triggered when the button is clicked.

  1. Event objects: Whenever an event takes place, an event object is instantiated. This object holds details about the event, including the event type, the element that initiated the event, and any other relevant data. This event object can be accessed as a parameter within the event handler function. Let’s look at an example:

const button = document.querySelector('#myButton');
button.addEventListener('click', function(event) {
console.log(event.type); // Logs 'click'
console.log(event.target); // Logs the button element
});

Common DOM events

There is a wide range of DOM events supported in JavaScript. Here are some common events, along with their descriptions and corresponding JavaScript event handlers:

DOM Event

Description

JavaScript Event Handler Syntax

click

Triggered when an element is clicked

element.addEventListener('click', function(event) {});

mouseover

Fired when the mouse pointer enters an element

element.addEventListener('mouseover', function(event) {});

mouseout

Fired when the mouse pointer exits an element

element.addEventListener('mouseout', function(event) {});

keydown

Captured when a key is pressed on the keyboard

element.addEventListener('keydown', function(event) {});

submit

Occurs when a form is submitted

element.addEventListener('submit', function(event) {});

load

Fired when the page is fully loaded

window.addEventListener('load', function(event) {});

resize

Fired when the browser window is resized

window.addEventListener('resize', function(event) {});

Code examples

Let’s look at some examples for better understanding.

Example 1: Removing list items using click event

Here is an example of handling events in a list:

  • HTML
  • CSS
  • JavaScript
Code example of click event

In the above JavaScript code:

  • Line 2: We get a reference to the parent element with the ID itemList. In this case, it’s the <ul> (unordered list) element that contains our list items.

  • Line 5: We add a click event listener to the itemList (the <ul> element). This listener will respond to click events occurring anywhere within the <ul> element, including its child <li> elements.

  • Line 7: We first check if the element that triggered the event (event.target) is an <li> element. We do this by comparing its tagName property to the string 'LI'. This conditional check ensures that we’re only responding to clicks on list items.

  • Line 9: If the clicked element is indeed an <li> element, we execute the code within this conditional block. In this case, we use event.target to refer to the specific <li> element that was clicked, and we call the remove() method on it. The remove() method removes the clicked list item from the parent <ul>, effectively deleting it from the list.

Example 2: Changing background color using multiple event handlers

Now, let’s look at another code example of a common DOM event.

  • HTML
  • CSS
  • JavaScript
Code example of a mouseover event

In the above JavaScript code:

  • Line 2: We get a reference to the parent element with the ID itemList. This is the <ul> (unordered list) element that contains our list items.

  • Line 5: We add a mouseover event listener to itemList (the <ul> element). This listener responds to mouseover events anywhere within the <ul> element, including its child <li> elements.

  • Line 6: Inside the event listener, we check if the element that triggered the event (event.target) is an <li> element by comparing its tagName property to the string 'LI'. This ensures that we only respond to mouseover events occurring on list items.

  • Line 7: If the mouseover event was triggered by an <li> element, we set the backgroundColor style of event.target (the specific <li> element that triggered the event) to #ffcc00. This highlights the list item with a yellow background color when hovered over.

  • Line 12–16: Similarly, we add a mouseout event listener to itemList to reset the background color of the <li> elements when the mouse is no longer hovering over them. We check if the event’s target element is an <li> element and reset the backgroundColor style of event.target to #007bff, changing it back to the original blue color.

Removing event listeners

Sometimes, we may need to remove an event listener to stop it from responding to events. We can use the removeEventListener() method for this.

  • HTML
  • CSS
  • JavaScript
Console
Code example of removing a event listener

In the above JavaScript code:

  • Line 5–11: We define a function handleClick() that logs "Button clicked!" and removes itself as an event listener.

  • Line 14: The addEventListener() method attaches handleClick to the button. After the button is clicked once, the event listener is removed.

Event propagation

DOM events have a unique property called propagation, which means events can “bubble” up or “capture” down through nested elements. Understanding this helps in managing complex event-handling situations.

  • HTML
  • CSS
  • JavaScript
Console
Code example of event propagation

In the above JavaScript code:

  • Lines 2–4: We select the body, container, and box elements. The container is the section element, and the box is the innermost div element.

  • Lines 7–9: We add an event listener to the body element. This listener logs Body clicked - bubbling phase when the body is clicked or when an event bubbles up to it. Here, false indicates that this listener responds in the bubbling phase.

  • Lines 11–19: Similarly, we add an event listener to the container (the section element) and the box (the div element) for the bubbling phase.

    • Line 13: It logs Container clicked - bubbling phase whenever the container itself is clicked or when an event bubbles up to it from its children.

    • Line 18: It logs Box clicked - bubbling phase whenever the box is clicked.

  • Lines 22–24: We add an event listener to the container for the capturing phase. Here, true specifies that this listener responds in the capturing phase, so it will capture events before they reach the box. When this listener is triggered, it logs Container clicked - capturing phase.

  • Lines 27–29: Similarly we add an event listener to the body element for the capturing phase. This listener logs Body clicked - capturing phase when it detects an event during the capturing phase.

  • Lines 32–35: We add another event listener to the box that stops event propagation. This listener logs Propagation stopped at box and then calls event.stopPropagation(), which prevents the event from bubbling up to parent elements. This line ensures that once the box is clicked, the event will not propagate further to the container or body.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

Which method is used to attach an event listener to an element?

A)

attachEvent()

B)

addEventListener()

C)

setEvent()

D)

createEvent()

Question 1 of 20 attempted

Conclusion

JavaScript event handling is a powerful tool for creating interactive and responsive web applications. By attaching event listeners to HTML elements and responding to user actions, we can enhance the user experience and make our web pages come alive. Understanding event listeners, event objects, and event propagation is essential for becoming proficient in JavaScript development.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


Which method registers an event handler for a DOM object?

The addEventListener() method registers an event handler for a DOM object. This method attaches a specified event (such as click, mouseover, etc.) to an HTML element, allowing a function to execute each time that event occurs on the element.

document.getElementById("myElement").addEventListener("click", function() {
  // Code to execute when the element is clicked
});

Which method is used to listen to events from DOM elements?

The addEventListener() method is also used to listen to events on DOM elements. It allows you to specify the event type and the function that should be called when the event occurs. Unlike older event-handling methods (like onclick), addEventListener() supports adding multiple event listeners for the same event type on an element.


How to perform a click event on DOM using JavaScript?

To handle a click event on a DOM element, first select the element, then add a click event listener using addEventListener() and provide a function to be executed when the element is clicked. You can also trigger a click event programmatically using the click() method.

// Handling a click event
document.getElementById("myButton").addEventListener("click", function() {
  console.log("Button was clicked!");
});

// Triggering a click event programmatically
document.getElementById("myButton").click();

How many types of events are in the HTML DOM?

The HTML DOM includes a wide variety of event types, categorized as:

  • Mouse events: e.g., click, dblclick, mouseover, mouseout, mousedown, mouseup
  • Keyboard events: e.g., keydown, keyup, keypress
  • Form events: e.g., submit, reset, focus, blur, change
  • Window events: e.g., load, resize, scroll, unload
  • Clipboard events: e.g., copy, cut, paste
  • Drag events: e.g., drag, drop, dragstart, dragend

These categories cover most user interactions and changes within the web page, allowing for comprehensive event handling and interactivity.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved