How to Trigger Resize Event Manually using Native JavaScript?

Introduction to Resize Event

Resize events are fired whenever the there is a change in the size of the document window or you can say when the document view is being resized. Now, this resize can trigger automatically in cases like changing device orientation from landscape to portrait or is someone changes the size of the browser intentionally. Now, this does help you to change certain aspects of the DOM. Below we have mentioned various use-cases where Resize Event can be used and can come into the picture.

Use Case

  1. When you want to align content on resize, for example, consider a div element which changes size, one can use this event in order to change the text alignment or other look and feel of the site.
  2. If there are some JavaScript Libraries that you are using or are planning to implement, there might be a situation where at times the Document View Resize event does not trigger at all, this leads to a situation that the resize of the various elements on the screen does not happen.

Implementation of Resize Event Listeners

  1. Simple implementation where you can catch the event and do the specified tasks in the callback
window.onresize = function() { // do a load of stuff };

2. Let’s refactor the code a bit, this will make the code simpler

window.onresize = doSomethingCool; 
function doSomethingCool() { //do a load of stuff }

3. You can directly use jQuery as well, it has a resize event.

Manually Triggering Resize Event without changing Document View Size

This is something we require at times when there is no resize of the Document View but we require some component to behave as if there was a change. This generally is used during situations when reflow does not happen automatically, we have to trigger a resize event manually so that the resize event listeners listen to it and resize the HTML Element.

window.dispatchEvent(new Event('resize'));

Caution

Do remember the fact, never run computationally expensive operations in the Resize Event listener such as DOM Modification or some heavy data calculations. It is always recommended to throttle these events using requestAnimationFrame, setTimeout .


Originally published at The Web Juice.