Skip to content

ES6 - Events

JavaScript enhances the interactivity of web pages through a mechanism called events. Events are part of the Document Object Model (DOM) and every HTML element can emit events that can trigger JavaScript code. Understanding and handling events effectively is crucial for dynamic web applications.

An event represents an action or occurrence recognized by the software, often triggered by user interaction (like a click or key press) or by the browser itself (like a page load or an error). When an event occurs on an element, we can respond to it by executing a function, known as an event handler or event listener.

While older JavaScript code might use HTML event attributes (e.g., onclick="myFunction()") or DOM element properties (e.g., element.onclick = myFunction;), the modern and recommended approach is to use the addEventListener() method. This method offers more flexibility, allowing multiple handlers for a single event, and better control over the event handling phases (capturing and bubbling).

The basic syntax for addEventListener() is: element.addEventListener(type, listenerFunction); Or with options: element.addEventListener(type, listenerFunction, optionsObjectOrUseCaptureBoolean);

  • Clean separation of HTML structure and JavaScript behavior.
  • Ability to add multiple event listeners for the same event type on an element.
  • Finer control over the event propagation phase (capturing vs. bubbling).
  • The removeEventListener() method can be used to detach handlers, preventing memory leaks.

The click event is one of the most common, occurring when a user clicks an element (typically with the primary mouse button).

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Click Event Example</title>
<style>
#messageArea {
margin-top: 10px;
padding: 10px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<p>Click the button below to see a message.</p>
<button id="helloButton">Say Hello</button>
<div id="messageArea"></div>
<script>
// Best practice: place script tags at the end of the body or use 'defer'
const button = document.getElementById('helloButton');
const messageArea = document.getElementById('messageArea');
function sayHello() {
messageArea.textContent = 'Hello World! The button was clicked.';
}
button.addEventListener('click', sayHello);
</script>
</body>
</html>

In this example, when the button with the ID helloButton is clicked, the sayHello function is executed. This function updates the text content of the div with the ID messageArea. This approach avoids document.write(), which can overwrite the entire page content and is generally not recommended for updating parts of a loaded page.

The submit event fires on a <form> element when it is submitted. This is a crucial event for form validation before data is sent to a server.

To prevent the default form submission (which usually reloads the page), you can call event.preventDefault() within the event listener.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Submit Event Example</title>
</head>
<body>
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<button type="submit">Submit</button>
</form>
<p id="formFeedback"></p>
<script>
const form = document.getElementById('myForm');
const feedback = document.getElementById('formFeedback');
function validateForm(event) {
event.preventDefault(); // Prevent default form submission
const usernameInput = document.getElementById('username');
if (usernameInput.value.trim() === '') {
feedback.textContent = 'Username cannot be empty!';
feedback.style.color = 'red';
return false; // Indicate validation failure
} else {
feedback.textContent = 'Form submitted successfully (simulated)!';
feedback.style.color = 'green';
// In a real application, you would now send data via fetch() or XMLHttpRequest
// form.submit(); // If you wanted to proceed with native submission after validation
return true; // Indicate validation success
}
}
form.addEventListener('submit', validateForm);
</script>
</body>
</html>

Here, the validateForm function is called when the form is submitted. event.preventDefault() stops the browser’s default submission process, allowing our script to perform validation. Based on the validation, it provides feedback to the user.

These events are triggered when the mouse pointer enters or leaves an element, respectively. They are useful for creating interactive effects like hover highlights or tooltips.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Mouseover/Mouseout Example</title>
<style>
#hoverDiv {
width: 200px; height: 100px;
background-color: lightblue;
text-align: center; line-height: 100px;
border: 1px solid blue;
}
</style>
</head>
<body>
<p>Move your mouse over the blue box:</p>
<div id="hoverDiv">
Hover over me!
</div>
<script>
const hoverDiv = document.getElementById('hoverDiv');
const originalText = hoverDiv.textContent;
hoverDiv.addEventListener('mouseover', function() {
hoverDiv.textContent = 'Mouse Over!';
hoverDiv.style.backgroundColor = 'lightgreen';
});
hoverDiv.addEventListener('mouseout', function() {
hoverDiv.textContent = originalText;
hoverDiv.style.backgroundColor = 'lightblue';
});
</script>
</body>
</html>

When the mouse pointer enters hoverDiv, its text and background color change. When the pointer leaves, they revert to their original state. Note how we store the original text to restore it.

The DOM standard defines a wide range of events. Here are some of the most common and useful ones. The ‘Triggered when’ column describes the condition that fires the event.

Event Type (Attribute Name: on...)Triggered when…
clickThe user clicks on an element.
dblclickThe user double-clicks on an element.
mousedownA mouse button is pressed down over an element.
mouseupA mouse button is released over an element.
mousemoveThe mouse pointer moves while over an element.
mouseoverThe mouse pointer moves onto an element or one of its children.
mouseoutThe mouse pointer moves out of an element or one of its children.
mouseenterThe mouse pointer moves onto an element (does not bubble).
mouseleaveThe mouse pointer moves out of an element (does not bubble).
keydownA key is pressed down.
keyupA key is released.
keypressA key that produces a character value is pressed down (deprecated; use keydown).
focusAn element receives focus (e.g., clicking in a text field).
blurAn element loses focus.
changeThe value of an input, select, or textarea element changes and the element loses focus.
inputThe value of an input or textarea element changes (fires immediately).
submitA form is submitted.
resetA form’s reset button is clicked.
loadA resource and its dependent resources have finished loading (e.g., a page, an image). Usually used on window or <img>.
unloadThe page is being unloaded (use with caution; beforeunload is often preferred for user confirmation).
beforeunloadFires right before the page is about to be unloaded. Can be used to prompt the user.
errorAn error occurs while loading an external resource (e.g., image, script) or in JavaScript execution.
resizeThe browser window is resized. Usually used on window.
scrollAn element’s scrollbar is being scrolled. Can be used on window or scrollable elements.
contextmenuThe right mouse button is clicked, triggering a context menu.
dragstartThe user starts dragging an element.
dragoverA dragged item is over a valid drop target.
dropA dragged item is dropped on a valid drop target.
playMedia (audio/video) begins to play.
pauseMedia (audio/video) is paused.
endedMedia (audio/video) has finished playing.
volumechangeThe volume of media (audio/video) has changed.

This list is not exhaustive. For a complete reference, consult the MDN Web Docs on Events. Remember to use addEventListener for modern, robust event handling.

Further Learning: Event object, event bubbling and capturing, event delegation. These are important concepts for advanced event management.