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.
Definition and Usage. The onresize event occurs when the browser window has been resized. Tip: To get the size of an element, use the clientWidth, clientHeight, innerWidth, innerHeight, outerWidth, outerHeight, offsetWidth and/or offsetHeight properties.
Answer: Use the addEventListener() Method You can simply use the addEventListener() method to register an event handler to listen for the browser window resize event, such as window. addEventListener('resize', ...) . The following example will display the current width and height of the browser window on resize.
In this case, we will use the native JavaScript event 'resize' in order to trigger the resize event as per our convenience. The syntax would be: $(window). trigger('resize'); $(<element>).
Best practice is to attach to the resize event.
window.addEventListener('resize', function(event) { ... }, true);
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.
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:
window.addEventListener('resize', function(event){ // do stuff here });
Here's a working sample.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With