Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript window resize event

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.

like image 204
Dead account Avatar asked Mar 13 '09 08:03

Dead account


People also ask

What is Resize event in JavaScript?

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.

How do I capture a Windows resize event?

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.

How do you trigger a resize event?

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>).


2 Answers

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.

like image 199
olliej Avatar answered Sep 25 '22 13:09

olliej


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.

like image 34
Jondlm Avatar answered Sep 24 '22 13:09

Jondlm