How to trigger the window resize event in JavaScript?

JavascriptJqueryEvents

Javascript Problem Overview


I have registered a trigger on window resize. I want to know how I can trigger the event to be called. For example, when hide a div, I want my trigger function to be called.

I found window.resizeTo() can trigger the function, but is there any other solution?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
    //do a load of stuff
}

In this example, you can call the doALoadOfStuff function without dispatching an event.

In your modern browsers, you can trigger the event using:

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

This doesn't work in Internet Explorer, where you'll have to do the longhand:

var resizeEvent = window.document.createEvent('UIEvents'); 
resizeEvent.initUIEvent('resize', true, false, window, 0); 
window.dispatchEvent(resizeEvent);

jQuery has the trigger method, which works like this:

$(window).trigger('resize');

And has the caveat:

> Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

You can also simulate events on a specific element...

function simulateClick(id) {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });

  var elem = document.getElementById(id); 

  return elem.dispatchEvent(event);
}

Solution 3 - Javascript

With jQuery, you can try to call trigger:

$(window).trigger('resize');

Solution 4 - Javascript

Combining pomber's and avetisk's answers to cover all browsers and not causing warnings:

if (typeof(Event) === 'function') {
  // modern browsers
  window.dispatchEvent(new Event('resize'));
} else {
  // for IE and other old browsers
  // causes deprecation warning on modern browsers
  var evt = window.document.createEvent('UIEvents'); 
  evt.initUIEvent('resize', true, false, window, 0); 
  window.dispatchEvent(evt);
}

Solution 5 - Javascript

A pure JS that also works on IE (from @Manfred comment)

var evt = window.document.createEvent('UIEvents'); 
evt.initUIEvent('resize', true, false, window, 0); 
window.dispatchEvent(evt);

Or for angular:

$timeout(function() {
    var evt = $window.document.createEvent('UIEvents'); 
    evt.initUIEvent('resize', true, false, $window, 0); 
    $window.dispatchEvent(evt);
});

Solution 6 - Javascript

I wasn't actually able to get this to work with any of the above solutions. Once I bound the event with jQuery then it worked fine as below:

$(window).bind('resize', function () {
    resizeElements();
}).trigger('resize');

Solution 7 - Javascript

just

$(window).resize();

is what I use... unless I misunderstand what you're asking for.

Solution 8 - Javascript

I believe this should work for all browsers:

var event;
if (typeof (Event) === 'function') {
    event = new Event('resize');
} else { /*IE*/
    event = document.createEvent('Event');
    event.initEvent('resize', true, true);
}
window.dispatchEvent(event);

Solution 9 - Javascript

Response with RxJS

Say Like something in Angular

size$: Observable<number> = fromEvent(window, 'resize').pipe(
            debounceTime(250),
            throttleTime(300),
            mergeMap(() => of(document.body.clientHeight)),
            distinctUntilChanged(),
            startWith(document.body.clientHeight),
          );

If manual subscription desired (Or Not Angular)

this.size$.subscribe((g) => {
      console.log('clientHeight', g);
    })

Since my intial startWith Value might be incorrect (dispatch for correction)

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

In say Angular (I could..)

<div class="iframe-container"  [style.height.px]="size$ | async" >..

Solution 10 - Javascript

window.resizeBy() will trigger window's onresize event. This works in both Javascript or VBScript.

window.resizeBy(xDelta, yDelta) called like window.resizeBy(-200, -200) to shrink page 200px by 200px.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzhongshuView Question on Stackoverflow
Solution 1 - JavascriptavetiskView Answer on Stackoverflow
Solution 2 - JavascriptFentonView Answer on Stackoverflow
Solution 3 - JavascriptBenjamin CrouzierView Answer on Stackoverflow
Solution 4 - JavascriptpfirpfelView Answer on Stackoverflow
Solution 5 - JavascriptpomberView Answer on Stackoverflow
Solution 6 - JavascriptBBQ SingularView Answer on Stackoverflow
Solution 7 - JavascriptMatt SichView Answer on Stackoverflow
Solution 8 - JavascriptwebaholikView Answer on Stackoverflow
Solution 9 - JavascriptSergio WilsonView Answer on Stackoverflow
Solution 10 - JavascriptT.O.View Answer on Stackoverflow