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 t
Solution for 2018+:
You should use ResizeObserver. It is 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 the document
but also on arbitrary elements
.
var ro = new ResizeObserver( entries => { for (let entry of entries) { const cr = entry.contentRect; console.log('Element:', entry.target); console.log(`Element size: ${cr.width}px x ${cr.height}px`); console.log(`Element padding: ${cr.top}px ; ${cr.left}px`); } }); // Observe one or multiple elements ro.observe(someElement);
Currently, Firefox, Chrome, and Safari support it. For other (and older) browsers you have to use a polyfill.