Skip to content

JavaScript Events

HTML events are “things” that happen to HTML elements, such as a mouse click, a key press, or a page finishing loading. JavaScript allows you to “react” to these events and execute code in response.

An HTML event can be triggered by browser actions (e.g., page load) or user interactions (e.g., clicking a button).

Here are some examples of HTML events:

  • An HTML web page has finished loading (load event).
  • An HTML input field’s value was changed (change event).
  • An HTML button was clicked (click event).
  • A key was pressed on the keyboard (keydown event).

When an event occurs, you often want to perform an action. JavaScript provides mechanisms to detect these events and run specific code, known as event handlers or event listeners.

The recommended way to handle events in modern JavaScript is by using the addEventListener() method. This method attaches an event handler function to an HTML element without overwriting existing event handlers.

Example using addEventListener():

// HTML: <button id="myButton">Click Me</button>
// JS:
const myButton = document.getElementById('myButton');
function showTime() {
document.getElementById('timeDisplay').textContent = new Date().toLocaleTimeString();
}
myButton.addEventListener('click', showTime);

This approach promotes separation of concerns (HTML structure vs. JavaScript behavior) and offers more flexibility (e.g., adding multiple listeners for the same event).

While still functional, older methods like inline event handler attributes and on<event> properties are generally less recommended for new development.

  1. Inline Event Handler Attributes:

HTML allows event handler attributes directly within HTML elements:

<!-- Less recommended for complex logic -->
<button onclick="alert('Button clicked!')">Show Alert</button>

Or calling a globally defined function:

<!-- HTML -->
<button onclick="displayDate()">What time is it?</button>
<p id="demo"></p>
<!-- JavaScript (must be global or accessible) -->
<script>
function displayDate() {
document.getElementById('demo').innerHTML = Date();
}
</script>
  1. on<event> Properties:

JavaScript can assign a function to an element’s on<event> property:

// HTML: <button id="anotherButton">Show Date</button>
// JS:
const_anotherButton = document.getElementById('anotherButton');
_anotherButton.onclick = function() {
document.getElementById('dateDisplay').textContent = new Date().toLocaleDateString();
};
// Note: This would overwrite any previous onclick handler on _anotherButton.
For modern development, addEventListener() is preferred due to its flexibility, ability to add multiple listeners, and better control over the event handling process (e.g., capturing vs. bubbling).

Here is a list of some common HTML events:

Event Type (for addEventListener)Description
clickThe user clicks an HTML element.
dblclickThe user double-clicks an HTML element.
mousedownA mouse button is pressed down over an element.
mouseupA mouse button is released over an element.
mousemoveThe mouse pointer moves 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.
keydownA key is pressed down.
keyupA key is released.
keypressA key that produces a character value is pressed down (deprecated by some browsers in favor of keydown).
focusAn element gets focus.
blurAn element loses focus.
changeThe value of an input, select, or textarea element has been changed.
inputThe value of an input or textarea element is changed (fires immediately).
submitA form is submitted.
loadA resource (like a page, image, or script) has finished loading.
unloadThe page is being unloaded (user navigates away).
resizeThe browser window has been resized.

This list is not exhaustive. For a comprehensive list, refer to MDN Web Docs on Event reference.

Event handlers enable a wide range of interactive functionalities:

  • Perform actions when a page loads (e.g., fetch data, initialize components).
  • Execute cleanup tasks when the page is closed or navigated away from.
  • Respond to user actions like button clicks, mouse movements, or key presses.
  • Validate user input in forms dynamically.
  • Create interactive menus, sliders, and other UI components.
  • And much more…

The addEventListener() method is the most robust way to let JavaScript work with events, providing control over how events are handled and allowing for clean separation of JavaScript logic from HTML markup.

You will learn more about events, event objects, and advanced event handling techniques (like event delegation) in subsequent HTML DOM chapters.