-->

JavaScript - Window - The Browser Object Model Part 4: Events and Event Listeners

The window object supports a variety of events, enabling interactivity.

Examples and Explanation

Window Resize Event

window.addEventListener("resize", () => {

  console.log("Window resized to:", window.innerWidth, window.innerHeight);

});

Explanation: The resize event triggers whenever the browser window is resized.

Scroll Event

window.addEventListener("scroll", () => {

  console.log("Scroll position:", window.scrollY);

});

Explanation: The scroll event captures vertical or horizontal scrolling.

Load and Unload Events

window.addEventListener("load", () => console.log("Page has fully loaded."));

window.addEventListener("beforeunload", (event) => {

  event.preventDefault();

  event.returnValue = "";

});

Explanation: These events help manage actions when a page loads or unloads.