How can I hook into a browser window resize event?
There's a jQuery way of listening for resize events but I would prefer not to bring it into my project for just this one requirement.
How can I hook into a browser window resize event?
There's a jQuery way of listening for resize events but I would prefer not to bring it into my project for just this one requirement.
The resize event should never be used directly as it is fired continuously as we resize.
Use a debounce function to mitigate the excess calls.
window.addEventListener('resize',debounce(handler, delay, immediate),false);
Here's a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.
This can be used like so...
It will never fire more than once every 200ms.
For mobile orientation changes use:
Here's a small library I put together to take care of this neatly.
Thanks for referencing my blog post at http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html.
While you can just hook up to the standard window resize event, you'll find that in IE, the event is fired once for every X and once for every Y axis movement, resulting in a ton of events being fired which might have a performance impact on your site if rendering is an intensive task.
My method involves a short timeout that gets cancelled on subsequent events so that the event doesn't get bubbled up to your code until the user has finished resizing the window.
Solution for 2018+:
You should use ResizeObserver. It will be a browser-native solution that has a much better performance than to use the
resize
event. In addition, it not only supports the event on thedocument
but also on arbitraryelements
.Currently, only Chrome supports it but other browsers will likely follow (soon). For now you have to use a polyfill.
First off, I know the
addEventListener
method has been mentioned in the comments above, but I didn't see any code. Since it's the preferred approach, here it is:Here's a working sample.