JavaScript events play a crucial role in browser-based programming. Understanding how events work and how to handle them is essential for building interactive web applications. In this article, we will explore JavaScript events and dive into event handling techniques.
Introduction
In the browser, JavaScript follows an event-driven programming model. This means that everything starts by listening for an event. An event can be triggered when the DOM is loaded, an asynchronous request finishes fetching data, a user clicks on an element, scrolls the page, or types on the keyboard. There are various types of events that can occur in a web application.
Event Handlers
To respond to events, we use event handlers - functions that are called when an event occurs. Multiple event handlers can be registered for the same event, and they will all be called when the event occurs. In JavaScript, there are three common ways to register an event handler:
Inline event handlers
Inline event handlers were commonly used in the past but are rarely used today due to their limitations. An inline event handler is defined directly in the HTML tag, like so:
<a href="site.com" onclick="doSomething();">A link</a>
DOM on-event handlers
DOM on-event handlers are used when an object has at most one event handler. This method is commonly used when handling XHR requests. Here’s an example:
window.onload = () => {
// window loaded
}
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
// ... do something
}
Using addEventListener()
addEventListener()
is the modern way to register event handlers. It allows us to register as many handlers as needed and is widely used. Here’s an example:
window.addEventListener('load', () => {
// window loaded
})
Note that addEventListener()
is not supported in IE8 and below. For older browsers, attachEvent()
is used instead.
Listening on Different Elements
Events can be listened to on different elements. We can listen to “global” events, like keyboard usage, by listening on the window
object. We can also listen to events happening on specific elements, such as a mouse click on a button, by targeting those elements. This is why addEventListener()
is sometimes called on window
and sometimes on a specific DOM element.
The Event Object
When an event occurs, an Event
object is passed to the event handler as the first parameter. This object contains useful properties and methods that provide information about the event. Some common properties include target
(the DOM element that triggered the event), type
(the type of event), and stopPropagation()
(used to stop event propagation in the DOM). There are also specific event objects like MouseEvent
, KeyboardEvent
, DragEvent
, and FetchEvent
that provide additional properties and methods specific to those events.
Event Bubbling and Event Capturing
Event bubbling and event capturing are two models that events use to propagate through the DOM. By default, all events bubble, which means they propagate from the clicked element to its parent elements. Event capturing, on the other hand, propagates from the top-level parent element to the clicked element. Event handlers are called in a specific order depending on the model being used. You can choose to use event capturing by setting the third argument of addEventListener()
to true
.
Stopping the Propagation
By default, an event on a DOM element will propagate to all its parent elements. However, you can stop the event from further propagation by calling the stopPropagation()
method of the event object. This is useful when you want to handle an event on a specific element without triggering the event handlers of its parent elements.
Popular Events
There are several common events that you will likely encounter when developing web applications. Some of these include:
Load
The load
event is fired on the window
and body
elements when the page has finished loading.
Mouse Events
Mouse events include click
, dblclick
, mousedown
, mousemove
, and mouseup
. These events are triggered when the user interacts with the mouse, such as clicking, double-clicking, or dragging.
Keyboard Events
Keyboard events include keydown
and keyup
and are triggered when the user interacts with the keyboard. These events can be used to detect which keys are being pressed or released.
Scroll
The scroll
event is fired on the window
object when the user scrolls the page. It can be used to track the current scrolling position.
Throttling
Some events like mousemove
and scroll
can fire multiple times during their duration, which can impact performance if not handled properly. Throttling is a technique used to control the frequency of event handler execution. By throttling an event, we can limit the number of times the event handler is called, reducing the impact on performance. Libraries like Lodash provide throttling implementations, but a simple implementation can be done using setTimeout()
to cache the event and limit its execution frequency.
let cached = null;
window.addEventListener('scroll', event => {
if (!cached) {
setTimeout(() => {
// you can access the original event at `cached`
cached = null;
}, 100);
}
cached = event;
});
Tags: JavaScript, Events, Event Handling, Event-driven Programming, Event Bubbling, Event Capturing, Throttling