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
You can use following approach which is ok for small projects
<body onresize="yourHandler(event)">
function yourHandler(e) {
console.log('Resized:', e.target.innerWidth)
}
<body onresize="yourHandler(event)">
Content... (resize browser to see)
</body>
jQuery is just wrapping the standard resize
DOM event, eg.
window.onresize = function(event) {
...
};
jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ, but I'd encourage you to test in Firefox, Safari, and IE.
The already mentioned solutions above will work if all you want to do is resize the window and window only. However, if you want to have the resize propagated to child elements, you will need to propagate the event yourself. Here's some example code to do it:
window.addEventListener("resize", function () {
var recResizeElement = function (root) {
Array.prototype.forEach.call(root.childNodes, function (el) {
var resizeEvent = document.createEvent("HTMLEvents");
resizeEvent.initEvent("resize", false, true);
var propagate = el.dispatchEvent(resizeEvent);
if (propagate)
recResizeElement(el);
});
};
recResizeElement(document.body);
});
Note that a child element can call
event.preventDefault();
on the event object that is passed in as the first Arg of the resize event. For example:
var child1 = document.getElementById("child1");
child1.addEventListener("resize", function (event) {
...
event.preventDefault();
});
<script language="javascript">
window.onresize = function() {
document.getElementById('ctl00_ContentPlaceHolder1_Accordion1').style.height = '100%';
}
</script>
The following blog post may be useful to you: Fixing the window resize event in IE
It provides this code:
Sys.Application.add_load(function(sender, args) { $addHandler(window, 'resize', window_resize); }); var resizeTimeoutId; function window_resize(e) { window.clearTimeout(resizeTimeoutId); resizeTimeoutId = window.setTimeout('doResizeCode();', 10); }
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.