Handling events in JavaScript: A beginner’s guide to modifying the DOM

Oladipupo Ishola
9 min readMar 25, 2023
Image by Elite Corner

JavaScript is a powerful programming language that can enhance web pages with interactivity and dynamic functionality. One of JavaScript's most important features is its ability to handle events, which are actions performed on a web page such as clicks, mouse movements, and key presses. Developers can create interactive web applications that respond to user input in real time by understanding how to handle events.

In addition to handling events, JavaScript can be used to modify the Document Object Model (DOM), which is a hierarchical representation of the elements on a web page. With the ability to modify the DOM, developers can dynamically change the content, style, and structure of web pages without having to reload the entire page.

In this beginner's guide to event handling in JavaScript, we'll look at how to register event listeners, write event handlers, and use JavaScript to modify the DOM. I'll also show you how to use event handling to create interactive web pages in practice. This guide will provide you with a solid foundation for working with events and the DOM in JavaScript, whether you're new to web development or looking to expand your skills.

You can also check out my other JavaScript beginner series, which are listed below.

For a quick refresher on DOM and accessing the DOM, you can check here

Before we begin, it is critical to understand events and event types in JavaScript. Now, let's get down to business.

Understanding JavaScript Events

JavaScript events are web page actions such as clicks, mouse movements, and key presses. They can be triggered by either the user or the web page. In order to handle events in JavaScript, you must first register an event listener for the element you want to monitor. The following are some examples of JavaScript events:

  1. Mouse events:
  • Click event: occurs when an element is clicked on by the user.
  • Mouseover event: occurs when an element is moved by the mouse pointer.
  • Mouseout event: occurs when the pointer of the mouse leaves an element.
  • Scroll event: occurs when the user scrolls the page

2. Keyboard events:

  • Keypress event: Occurs when the user presses a key on the keyboard
  • Keydown event: Occurs when the user presses a key down
  • Keyup event: Occurs when the user releases a key

3. Form events:

  • Submit event: Occurs when the user submits a form
  • Change event: Occurs when the user changes the value of a form element
  • Focus event: Occurs when an element gets focus
  • Blur event: Occurs when an element loses focus

4. Document events:

  • DOMContentLoaded event: Occurs when the HTML document has been completely loaded and parsed
  • Load event: Occurs when all external resources (images, scripts, etc.) have been loaded
  • Unload event: Occurs when the user leaves the page or closes the browser window

To register an event listener, you need to specify the type of event you want to listen for and the function that should be executed when the event occurs. Here’s an example of registering a click event listener:

const button = document.querySelector('button');

button.addEventListener('click', function() {
alert('Button clicked!');
});

In this example, we first select the button element using the querySelector method. Then we use the addEventListener method to register a click event listener for the button element. The second parameter of the addEventListener method is a function that will be executed when the button is clicked. In this case, we simply show an alert message that says "Button clicked!"

In a similar manner, you can register event listeners for other types of events. For example, here’s how you would register a keypress event listener:

const input = document.querySelector('input');

input.addEventListener('keypress', function(event) {
console.log(`Key pressed: ${event.key}`);
});

In this example, we'll choose an input element and add a keypress event listener to it. The event listener function takes an event parameter that contains information about the event that occurred. In this case, we log the key that was pressed on the console.

Modifying the DOM

Once you've mastered the fundamentals of JavaScript events, you can start modifying the Document Object Model (DOM) to create dynamic web pages. The Document Object Model (DOM) is a tree-like structure that represents the HTML elements on a web page. You can add, remove, and modify elements on the page by manipulating the DOM with JavaScript.

Here are some common DOM manipulation techniques in JavaScript:

  1. Selecting elements:
  • document.getElementById(): Selects an element by its ID
  • document.querySelector(): Selects the first element that matches a CSS selector
  • document.querySelectorAll(): Selects all elements that match a CSS selector

2. Adding elements:

  • document.createElement(): Creates a new HTML element
  • parentElement.appendChild(): Adds an element to the end of a parent element
  • parentElement.insertBefore(): Inserts an element before a specified child element

3. Removing elements:

  • parentElement.removeChild(): Removes a child element from a parent element

4. Modifying element attributes and content:

  • element.setAttribute(): Sets the value of an attribute on an element
  • element.getAttribute(): Gets the value of an attribute on an element
  • element.innerHTML: Sets or gets the HTML content inside an element
  • element.textContent: Sets or gets the text content inside an element

Here's an example of a new element being created and added to the DOM:

const parentElement = document.querySelector('.container');
const newElement = document.createElement('div');
newElement.textContent = 'Hello, world!';
parentElement.appendChild(newElement);

In this example, we use the querySelector method to select a parent element with the class name "container." Then, using the createElement method, we create a new "div" element and set its text content to "Hello, world!" Finally, we use the appendChild method to append the new element to the end of the parent element.

Similar techniques can be used to remove or modify existing elements on the page. For instance, here's how to remove an element from the DOM:

const elementToRemove = document.getElementById('myElement');
const parentElement = elementToRemove.parentElement;
parentElement.removeChild(elementToRemove);

In this example, we use the getElementById method to select an element with the ID myElement. Then, using the parentElement property, we get its parent element and use the removeChild method to remove the element from the parent.

Event Handlers

You can add event handlers to your web pages to make them even more interactive. Event handlers are functions that are called when an element experiences a specific event, such as a button click or a mouse hover.

Here are some examples of common events that you can handle in JavaScript:

  • click: activated upon clicking on an element
  • mouseover: When the mouse pointer enters or hovers over an element, the event is triggered
  • mouseout: triggered when the mouse pointer leaves an element
  • keydown: triggered when a keyboard key is pressed down
  • keyup: triggered when a keyboard key is released
  • submit: triggered when a form is submitted

The "addEventListener" method can be used to add an event handler to an element. An example of adding a click event handler to a button is shown below:

const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('Button clicked!');
});

In this example, we use the "querySelector" method to select a button element and the "addEventListener" method to add a click event handler. When the button is clicked, the event handler simply logs a message to the console.

You can also use the "addEventListener" method to pass a named function, which makes your code more modular and easier to read. As an example, consider the following:

function handleButtonClick() {
console.log('Button clicked!');
}

const button = document.querySelector('button');
button.addEventListener('click', handleButtonClick);

In this example, we define a named function called "handleButtonClick," which, when called, logs a message to the console. Then, using the "addEventListener" method, we add the function as the event handler for the button click event.

Similar methods can be used to add event handlers for other types of events. For instance, here's how to add a submit event handler to a form:

const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
console.log('Form submitted!');
});

In this example, we use the "querySelector" method to select a form element and the "addEventListener" method to add a submit event handler. When the form is submitted, the event handler functions log a message to the console. We also use the event object's "preventDefault" method to prevent the form from submitting and reloading the page.

Practical Applications

Now that you know how to use events and event handlers in JavaScript, let's look at some real-world examples. Here are a few examples:

  1. Form Validation

Events can be used to validate form input in real time, giving users immediate feedback if they enter incorrect information. You can, for example, use the "input" event to determine whether a user has entered a valid email address as they type. As an example, consider the following:

const emailInput = document.querySelector('#email');
emailInput.addEventListener('input', function(event) {
const email = event.target.value;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
emailInput.setCustomValidity('Please enter a valid email address.');
} else {
emailInput.setCustomValidity('');
}
});

In this example, we choose an input element with the ID "email" and attach an "input" event handler to it. The event handler checks to see if the value of the input field matches a regular expression for a valid email address. If the input is invalid, we set a custom error message on the input field using the setCustomValidity method. If the input is correct, the error message is removed.

2. Dynamic User Interfaces

Events can be used to create dynamic user interfaces that respond in real-time to user input. For example, you can use the 'click' event to show or hide elements based on user input. As an example, consider the following:

const toggleButton = document.querySelector('#toggle');
const content = document.querySelector('#content');
toggleButton.addEventListener('click', function() {
content.classList.toggle('hidden');
});

We choose a button element with the ID 'toggle' and a content element with the ID 'content' in this example. The button now has a "click" event handler that toggles the "hidden" class on the content element. By clicking the button, users can show or hide the content.

3. Animated Effects

Events can be used to create animated effects that react to user input. You can use the mouseover and mouseout events, for example, to create hover effects on elements. Here's an illustration:

const box = document.querySelector('#box');
box.addEventListener('mouseover', function() {
box.style.backgroundColor = 'red';
});
box.addEventListener('mouseout', function() {
box.style.backgroundColor = 'blue';
});

In this example, we'll use the ID "box" to select a div element. When the user hovers over the box, we add a mouseover event handler that changes the background color to red. We also include a mouseout event handler that returns the background color to blue when the user moves the mouse away from the box.

These are just a few of the many practical applications of JavaScript events and event handlers. You can create dynamic and engaging user interfaces for your web pages by combining events with other web development technologies such as CSS and HTML.

Conclusion

We've covered the fundamentals of how events and event handlers work in JavaScript, as well as some practical applications, in this beginner's guide to modifying the DOM with events. You can create dynamic user interfaces that respond to user input in real-time by using events.

While this guide only covers the fundamentals of JavaScript events, it should serve as a good starting point for you to explore more advanced concepts. You'll discover new and creative ways to improve the functionality and user experience of your web pages as you continue to work with events and event handlers.

Remember that practice is the key to mastering events. So, continue experimenting with various types of events and event handlers, and don't be afraid to try new things. With time and practice, you will gain the skills and knowledge required to become an expert JavaScript developer.

Thank you for taking the time to read this! I hope this guide has been useful in getting you started with JavaScript events and event handlers. If you have any questions or comments, please leave them in the comments section below.

--

--

Oladipupo Ishola

Tech Writer | Mentor & Code Instructor | Bootcamp Grad | Full Stack Developer | Frontend Developer | Backend Developer | MLH ’21 Alum