426

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?

0

10 Answers 10

833
window.dispatchEvent(new Event('resize'));
15
  • 12
    seems to work with Chrome, FF, Safari, but not: IE !
    – Davem M
    Mar 18, 2014 at 22:14
  • 16
    jQuery's trigger does not actually trigger the native "resize" event. It only triggers event listeners that have been added using jQuery. In my case, a 3rd party library was listening directly to the native "resize" event and this is the solution that worked for me.
    – chowey
    May 26, 2014 at 21:09
  • 2
    Great and simple solution. Although, I think you should add some code for IE compatibility (as far as I see, for IE, we have to use window.fireEvent)
    – Victor
    Apr 1, 2015 at 7:58
  • 37
    this didnt work on all devices for me. i had to trigger the event like this: var evt = document.createEvent('UIEvents'); evt.initUIEvent('resize', true, false, window, 0); window.dispatchEvent(evt);
    – Manfred
    Jun 16, 2015 at 14:42
  • 21
    It fails with "Object doesn't support this action" in my IE11
    – pomber
    Aug 9, 2015 at 0:46
488

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);
}
6
  • 6
    Your anonymous function is unnecessary. window.onresize = doALoadOfStuff; Also, this doesn't answer the question, pinouchon's answer below is the correct answer. Sep 5, 2013 at 18:18
  • 44
    To Googler's: Have a look at @avetisk's answer. Oct 17, 2015 at 11:31
  • 1
    It's a good idea to decouple, but in my/this case, it doesn't work. Just calling the resize method doesn't work because if the window resize isn't triggered various other div/containers won't have the proper height set.
    – PandaWood
    Jun 10, 2016 at 8:02
  • @PandaWood - then my last example is better in your case.
    – Fenton
    Jun 10, 2016 at 8:10
  • 1
    much obliged mate. this was really helpfull
    – Desper
    May 7, 2021 at 8:02
160

With jQuery, you can try to call trigger:

$(window).trigger('resize');
6
  • 3
    A use case for this is when a jQuery plugin uses window resize events to be responsive, but you have a collapsing sidebar. The plugin's container gets resized, but the window does not.
    – isherwood
    Oct 15, 2014 at 19:10
  • 4
    No need for JQuery indeed but I prefer JQuery solution as my product uses JQuery extensively.
    – Sri
    May 15, 2015 at 21:52
  • Where would this be added to resize a wordpress page after it has loaded?
    – SAHM
    Aug 18, 2016 at 3:58
  • This is not working for me in latest Chrome, this answer does: stackoverflow.com/a/22638332/1296209
    – webaholik
    Sep 15, 2018 at 19:27
  • 3
    this is what I initially tried- it didn't work, but window.dispatchEvent(new Event('resize')); did Dec 5, 2019 at 16:48
72

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);
}
2
  • 1
    This is a good way to do it across browsers without using jQuery.
    – kgx
    Jan 12, 2018 at 14:50
  • no idea why this isn't the top answer......this is better than the "either or" answers that are accepted....
    – SPillai
    Oct 31, 2018 at 20:32
54

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);
});
3
  • 4
    Unfortunately the documentation for UIEvent.initUIEvent() says Do not use this method anymore as it is deprecated. The createEvent docs say "Many methods used with createEvent, such as initCustomEvent, are deprecated. Use event constructors instead." This page looks promising for UI events. Dec 3, 2015 at 5:27
  • 9
    True, but IE11 doesn't support the new Event() method. I think as a hack against older browsers you could do something like if (Event.prototype.initEvent) { /* deprecated method */ } else { /* current method */ }. Where the current method is the avetisk's answer.
    – BrianS
    Jan 19, 2016 at 23:31
  • @pomber Thanks for the solution, Actually I was trying to trigger custom event for window resize to resize my chart... your solution save my day Feb 15, 2019 at 15:08
15

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');
1
  • Works in Chrome today.
    – webaholik
    Sep 15, 2018 at 7:18
9

just

$(window).resize();

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

1
  • 3
    And even if you have jQuery, it only triggers events that were bound with jQuery.
    – adamdport
    Aug 11, 2016 at 17:50
2

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);
2
  • Works great in Chrome and FF, but didn't work in IE11
    – Collins
    Mar 30, 2020 at 7:58
  • @Collins - thanks for the update, thought I had verified this on IE11...I'll try to take some time later to update this, thanks for the feedback.
    – webaholik
    Mar 30, 2020 at 12:37
0

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" >..
-2

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.

4
  • 3
    Why is this marked down? Is it incorrect? Is it browser dependent?
    – Peter Wone
    May 4, 2014 at 4:08
  • 3
    This doesn't work in any browser: Chrome, Firefox, IE, Firefox tested.
    – fregante
    Sep 25, 2015 at 18:28
  • 1
    Firefox 7+, and probably other modern browsers, no longer allow calling this method in most cases. In addition, it's not desirable to actually have resize the window in order to trigger the event.
    – user247702
    Aug 10, 2016 at 9:04
  • Both resizeBy() and resizeTo() are working fine in latest stable Chrome ver. 76.0
    – VanagaS
    Sep 21, 2019 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.