Explain Codes LogoExplain Codes Logo

Javascript window resize event

javascript
event-handling
debounce
resize-observer
Nikita BarsukovbyNikita Barsukov·Dec 5, 2024
TLDR

Track resize events using window.addEventListener:

window.addEventListener('resize', () => { console.log(`Size: ${window.innerWidth}x${window.innerHeight}`); // The new size is so hot right now! });

Prints the new window size upon every resize.

Window Resize: Handling the Changes

Handling resize events ensures compatibility and responsiveness across a multitude of devices and browsers.

A Dress for All Seasons: Supporting Multiple Browsers

When thinking of web browser compatibility, be it Firefox, Safari, or IE, or considering distinct events in mobile browsers like orientationchange, adapting your code is key.

if (window.addEventListener) { window.addEventListener('resize', handleResize); } else if (window.attachEvent) { window.attachEvent('onresize', handleResize); } else { // If neither exists, it's not you, it's the browser 🤷‍♀️ }

Marching to the Beat: Debouncing Resize Events

Mitigating performance issues with a debounce function ensures the event handler does not turn into a hyperactive kid who's had too much sugar:

function debounce(func, wait) { let timeout; // Timeout, go sit in the corner! return function() { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, arguments), wait); }; }

In this version of musical chairs, resize always waits for the song to pause before making a move.

Orientation Shakeup: Handling Mobile Devices

On mobile devices, resizing is supersized with an extra side of orientationchange:

window.addEventListener('orientationchange', () => { // Remember: Landscape or portrait, you're beautiful just the way you are! });

Elevating Resize Event Handling

ResizeObserver: Your Personal Tailor

Introducing ResizeObserver, your specialist for element-specific size changes:

const ro = new ResizeObserver(entries => { // Your clothes fit you so well, who's your tailor! });

This "tailor" adjusts to every little change, ensuring a perfect fit.

Advanced Optimization: Throttling

Throttling, aka the responsible elder sibling of debouncing, limits the rate of function execution:

function throttle(func, wait) { let timeout; return function() { if (!timeout) { timeout = setTimeout(() => { func.apply(this, arguments); timeout = null; }, wait); } }; }

In this version, resize gets to play, but only within time limits.

Accessibility: Beyond Sizing and Scrolling

We must also consider potential disruptions to assistive technologies:

window.addEventListener('resize', () => { // Remember: Accessibility is a right, not a privilege! });