Skip to main content

Window Events in JavaScript (Live Playground)

In this tutorial, we'll explore how to work with window events in JavaScript to create more dynamic and responsive web pages. We'll cover common window events such as load, unload, and resize.

Common window events

Here are some common window events you might encounter when working with JavaScript:

  • load: Triggered when the entire content of a page, including all images and external resources, has finished loading.
  • unload: Triggered when the user navigates away from the page or closes the browser window.
  • resize: Triggered when the browser window is resized.

Handling window events

To handle window events in JavaScript, you can use the addEventListener() method. Here's an example of how to handle the load event:

<!DOCTYPE html>
<html>
<head>
<title>Window Load Event Example</title>
</head>
<body>
<h1>Window Load Event</h1>

<script>
// Function to handle the load event
function handleLoad() {
setTimeout(() => {
console.log('Window loaded!');
});
}

// Add a load event listener to the window object
window.addEventListener('load', handleLoad);
</script>
</body>
</html>

In this example, we define a handleLoad() function that logs a message to the console when the window is fully loaded. We then use the addEventListener() method to register the handleLoad() function as a callback for the load event on the window object.

Live Playground, Try it Yourself

Example: Detecting window resize

Now let's create an example where we detect when the window is resized:

<!DOCTYPE html>
<html>
<head>
<title>Window Resize Detection Example</title>
</head>
<body>
<h1>Window Resize Event</h1>

<script>
// Function to handle the resize event
function handleResize() {
console.log('Window resized!');
}

// Add a resize event listener to the window object
window.addEventListener('resize', handleResize);
</script>
</body>
</html>

In this example, we define a handleResize() function that logs a message to the console when the window is resized. We then use the addEventListener() method to register the handleResize() function as a callback for the resize event on the window object.

Live Playground, Try it Yourself