YouTip LogoYouTip

Ev Onresize

## HTML onresize Event Attribute The `onresize` event attribute fires when a document view (the window) or an element is resized. It is commonly used to dynamically adjust layouts, recalculate dimensions, or update UI components when the user resizes the browser window. --- ## Browser Support The `onresize` event attribute is fully supported by all major modern web browsers: * Google Chrome * Microsoft Edge / Internet Explorer * Mozilla Firefox * Safari * Opera --- ## Definition and Usage * The `onresize` attribute triggers a script when the browser window is resized. * It is most commonly attached to the `` element (representing the window object). * **HTML 4.01 vs. HTML5:** There are no differences in how this event behaves between HTML 4.01 and HTML5. --- ## Syntax You can use the `onresize` attribute directly within an HTML tag: ```html ``` ### Attribute Values | Value | Description | | :--- | :--- | | *script* | Specifies the JavaScript code or function to execute when the `onresize` event is triggered. | --- ## Code Examples ### Example 1: Basic Inline Usage on the `` This example displays an alert message whenever the browser window is resized. ```html onresize Event Demo

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. ```html Display Window Size

Resize 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.
← Ev OnunloadEv Onload β†’