How to Trigger the Window Resize Event in JavaScript?
Here's the shortcut to simulate a window resize event:
This code dispatches a 'resize' event, immediately triggering all registered resize event handlers. It's quite handy when testing responsive designs or when you need to trigger responsive scripts without manually adjusting browser window size.
Resize Triggering: Scenario Breakdown
When would you trigger resize manually?
In practical terms:
-
Responsive Design Testing: It's useful to trigger resizing programmatically for testing responsive designs. It's like the effort-saver mode, so you don't need to manually drag your browser edges every time.
-
Layout Adjustments: These are situations where layout dimensions change, but the viewport stays the same. For instance, when sidebar is collapsed or an element is hidden or adjusted.
-
Custom UI Components: Specific custom elements might need to adapt to window size the same way as standard ones, ensuring consistent UI behaviour.
Resize event in non-modern browsers
While window.dispatchEvent(new Event('resize'));
works a charm in modern browsers, Internet Explorer prefers its own way:
And for jQuery users, we do have a shorthand:
Remember the window.resizeTo()
. It’s like the "Do not touch" sign in the museum. It resizes the actual window, not the elements, which is a different behaviour and often disabled in contemporary browsers due to UX considerations.
Handling Events: From Window to Elements
Triggering events on specific elements
Sometimes we need to stimulate events on specific elements, not the entire window. Here's the same dispatchEvent
method coming handy:
Custom function for event simulation
To facilitate event simulations across your code, you might consider a reusable custom function:
On the fly mouse event simulation
With MouseEvent
constructor, you can simulate mouse-related events such as click, mouseover, mouseout:
Remember to pay attention to deprecation warnings and use the right method for event initialization in the ever-evolving browsers.
Asynchronous Operations and Window Resize
Post async operation resize trigger
In an Angular context, for instance, there could be scenarios where you need to trigger window resize after certain asynchronous operations. Here's where $timeout
comes into play:
Cross-Browser Compatibility: The Ultimate Strategy
It's usually a prudent decision to join forces of multiple solutions to ensure compatibility across different browsers. Always consider checking for the existence of certain constructors or methods before utilising them, and fall back on older methods when necessary.
Was this article helpful?