Skip to content

DOM Events

The HTML DOM (Document Object Model) allows JavaScript to react to HTML events, making web pages interactive. Events are actions that occur, such as a user clicking an element, a page finishing loading, or an input field changing.

Example of making a button interactive:

// HTML:
// <button id="interactiveButton">Click Me</button>
// <p id="messageArea"></p>
// JavaScript:
const button = document.getElementById('interactiveButton');
const messageArea = document.getElementById('messageArea');
if (button && messageArea) { // Ensure elements exist
button.addEventListener('click', function() {
messageArea.textContent = 'Button was clicked at ' + new Date().toLocaleTimeString();
});
button.addEventListener('mouseover', function() {
button.style.backgroundColor = 'lightgreen';
});
button.addEventListener('mouseout', function() {
button.style.backgroundColor = ''; // Reset background
});
}

JavaScript code can be executed when an event occurs. This code is known as an event handler or event listener.

Common ways to assign event handlers (with addEventListener() being the recommended modern approach):

Section titled “1. Using addEventListener() (Recommended):”

This is the most flexible and standard way. It allows adding multiple listeners to the same element for the same event.

const myElement = document.getElementById('myElem');
myElement.addEventListener('click', function() {
this.innerHTML = 'Clicked with addEventListener!'; // 'this' refers to myElement
});

You can assign a function directly to an element’s on<event> property (e.g., onclick, onmouseover). This method only allows one handler per event type; assigning a new function overwrites the previous one.

const anotherElement = document.getElementById('anotherElem');
anotherElement.onclick = function() {
this.innerHTML = 'Clicked via onclick property!'; // 'this' refers to anotherElement
};
Section titled “3. Inline HTML event attributes (Less Recommended):”

Event handlers can be specified directly in HTML attributes. This mixes JavaScript logic with HTML structure, which is generally discouraged for larger applications as it can make code harder to maintain.

<h1 onclick="this.innerHTML='Oops!'">Click on this text!</h1>

Or calling a function defined elsewhere (the function must be in the global scope or accessible):

<!DOCTYPE html>
<html>
<head>
<title>Event Example</title>
<script>
function changeText(element) {
element.innerHTML = "Text Changed!";
}
</script>
</head>
<body>
<h1 onclick="changeText(this)">Click me!</h1>
</body>
</html>

Inside an event handler function attached using element.addEventListener('event', function() { ... }) or element.on<event> = function() { ... }, the this keyword typically refers to the HTML element to which the event listener is attached (the event.currentTarget).

However, if you use an arrow function (() => { ... }) as the handler, this will retain its value from the surrounding (lexical) scope, not the element itself. Be mindful of this difference.

const demoButton = document.getElementById('demoBtn');
if (demoButton) {
// Using a regular function, 'this' is the button
demoButton.addEventListener('click', function() {
console.log(this.tagName); // Logs 'BUTTON'
this.textContent = 'Clicked!';
});
// Using an arrow function, 'this' depends on the outer scope
// (e.g., 'window' if defined globally, or an outer object if in a method)
// demoButton.addEventListener('mouseover', () => {
// console.log(this); // Might not be the button element
// demoButton.style.color = 'red'; // Safer to use the element variable directly
// });
}

Here are some frequently used DOM events:

The load event fires when a resource and its dependent resources have finished loading. For the window object, it fires after the whole page (HTML, CSS, images, scripts) is fully loaded.

The DOMContentLoaded event (on document) is often preferred for page initialization logic as it fires as soon as the HTML document has been completely parsed, without waiting for stylesheets, images, and subframes to finish loading.

window.addEventListener('load', function() {
console.log('Page fully loaded (including images, CSS).');
});
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM fully loaded and parsed. Safe to manipulate DOM.');
// Example: check for saved user preferences from localStorage
// checkUserPreferences();
});

change (on <input>, <select>, <textarea>):

Section titled “change (on <input>, <select>, <textarea>):”

The change event fires when the value of an element has been committed by the user. For text inputs, this usually means when the element loses focus after its value was modified. For select boxes, checkboxes, and radio buttons, it fires immediately when the selection changes.

const mySelect = document.getElementById('mySelect');
if (mySelect) {
mySelect.addEventListener('change', function() {
console.log('Selected value: ' + this.value);
// Update UI based on selection
});
}

The input event fires synchronously when the value of an <input> or <textarea> element is changed. This is useful for real-time feedback as the user types.

const nameInput = document.getElementById('nameField');
if (nameInput) {
nameInput.addEventListener('input', function() {
document.getElementById('livePreview').textContent = 'Hello, ' + this.value;
});
}

Mouse Events: mouseover, mouseout, mousedown, mouseup, click

Section titled “Mouse Events: mouseover, mouseout, mousedown, mouseup, click”
  • mouseover: Fires when the mouse pointer enters an element or one of its children.

  • mouseout: Fires when the mouse pointer leaves an element or one of its children.

  • mousedown: Fires when a mouse button is pressed down on an element.

  • mouseup: Fires when a mouse button is released over an element.

  • click: Fires after a mousedown and mouseup event on the same element.

  • keydown: Fires when a key is pressed down.

  • keyup: Fires when a key is released.

  • focus: Fires when an element receives focus.

  • blur: Fires when an element loses focus.

Example with multiple mouse events:

const interactiveDiv = document.getElementById('interactiveBox');
if (interactiveDiv) {
interactiveDiv.addEventListener('mousedown', function() {
this.style.backgroundColor = 'blue';
this.textContent = 'Pressed!';
});
interactiveDiv.addEventListener('mouseup', function() {
this.style.backgroundColor = 'lightblue';
this.textContent = 'Released!';
});
}

For a comprehensive list of all HTML DOM events and their properties, consult the MDN Web Docs on Event reference.