Try resizing the browser window to trigger the onresize event.
``` ### Example 2: Dynamically Displaying Window Dimensions A more practical use case is capturing and displaying the current width and height of the window in real-time. ```htmlResize the window to see the dimensions update:
Width: -, Height: -
``` --- ## Best Practices and Considerations ### 1. Performance and Debouncing The `onresize` event fires continuously as the user drags the window corner. Executing heavy DOM manipulation or complex calculations directly inside this event can cause severe performance lag. To optimize performance, it is highly recommended to use a **debounce** or **throttle** function to limit how often the event handler runs. ```javascript // Debounce helper to limit execution rate function debounce(func, delay) { let timer; return function(...args) { clearTimeout(timer); timer = setTimeout(() => func.apply(this, args), delay); }; } // Attach debounced handler in JavaScript instead of HTML window.onresize = debounce(() => { console.log("Resized event handled efficiently!"); }, 250); // Executes 250ms after the user stops resizing ``` ### 2. JavaScript Event Binding While using the HTML attribute `` works, modern web development standards recommend separating HTML markup from JavaScript behavior. You should bind the event using `addEventListener` in your JavaScript file: ```javascript window.addEventListener('resize', myFunction); ``` ### 3. Resizing Non-Window Elements Historically, the `onresize` event only reliably fired on the `window` object. If you need to monitor size changes on specific HTML elements (like a ``), use the modern **`ResizeObserver` API** instead of the `onresize` attribute.
YouTip