421

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?

Costique
  • 23,712
  • 4
  • 76
  • 79
zhongshu
  • 7,748
  • 8
  • 41
  • 54

10 Answers10

824
window.dispatchEvent(new Event('resize'));
Alien
  • 3,658
  • 1
  • 16
  • 33
avetisk
  • 11,651
  • 4
  • 24
  • 37
  • 12
    seems to work with Chrome, FF, Safari, but not: IE ! – Davem M Mar 18 '14 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 '14 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 01 '15 at 07: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 '15 at 14:42
  • 1
    Victor && @Manfred: please specify for which version of which browser(s), I'll quote your comments in my answer. – avetisk Jun 27 '15 at 07:47
  • 21
    It fails with "Object doesn't support this action" in my IE11 – pomber Aug 09 '15 at 00:46
  • Try Manfred's solution @pomber. It is the only one that worked for me for IE Edge and may work for IE11 as well. – Robert Waddell Dec 02 '15 at 21:45
  • 1
    Thanks @RobertWaddell, actually I've already done that and posted it as an answer here – pomber Dec 03 '15 at 02:36
  • 1
    I had to put this event in a `setTimeout` because it was likely getting fired too soon after the DOM manipulation that I was trying to get resized. – Matt Kneiser Jun 29 '16 at 21:49
  • Anyidea why jquery $(window).trigger('resize') not working? – Qiang Jun 29 '16 at 23:22
  • 1
    this worked good for me, better than $(window).trigger('resize') – Fernando Gabrieli Feb 15 '17 at 20:38
  • 1
    Just to add, this did work for me but the jQuery version $(window).trigger('resize') did not. jQuery must do something slightly different. – chris Jun 06 '17 at 14:31
  • 1
    This worked for me, where the jQuery version posted in other answers here didn't. So it seems the jQuery version isn't exactly the same – Master_T Feb 05 '19 at 15:50
  • It's worth noting this is the only way to trigger all resize handlers (third party or not) while in most cases jQuery's $(window).trigger('resize') will call resize event handlers created by jQuery itselt. – J. Wrong Apr 24 '22 at 00:19
  • 'evt.initUIEvent' is deprecated as it is written in above comment by @Manfred – Ali Rehman Sep 07 '22 at 08:13
483

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);
}
BuZZ-dEE
  • 6,075
  • 12
  • 66
  • 96
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • 6
    Your anonymous function is unnecessary. window.onresize = doALoadOfStuff; Also, this doesn't answer the question, pinouchon's answer below is the correct answer. – Dennis Plucinik Sep 05 '13 at 18:18
  • 44
    To **Google**r's: Have a look at @avetisk's answer. – Fabian Lauer Oct 17 '15 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 '16 at 08:02
  • @PandaWood - then my last example is better in your case. – Fenton Jun 10 '16 at 08:10
  • window.dispatchEvent(new Event('resize')); causes an exception in latest Chrome: "Uncaught TypeError: Failed to execute 'dispatchEvent' on 'EventTarget': parameter 1 is not of type 'Event'." – Johncl Sep 07 '20 at 08:10
  • 1
    much obliged mate. this was really helpfull – Desper May 07 '21 at 08:02
159

With jQuery, you can try to call trigger:

$(window).trigger('resize');
Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
  • 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 '14 at 19:10
  • 4
    No need for JQuery indeed but I prefer JQuery solution as my product uses JQuery extensively. – Sri May 15 '15 at 21:52
  • Where would this be added to resize a wordpress page after it has loaded? – SAHM Aug 18 '16 at 03:58
  • This is not working for me in latest Chrome, this answer does: https://stackoverflow.com/a/22638332/1296209 – webaholik Sep 15 '18 at 19:27
  • Sometime I use window.dispatchEvent to trigger event, but it didn't work.But jquery's trigger still work. So nice with jquery. – alan9uo Apr 26 '19 at 10:44
  • 3
    this is what I initially tried- it didn't work, but `window.dispatchEvent(new Event('resize'));` did – user2682863 Dec 05 '19 at 16:48
71

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);
}
pfirpfel
  • 2,176
  • 2
  • 15
  • 12
  • 1
    This is a good way to do it across browsers without using jQuery. – kgx Jan 12 '18 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 '18 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);
});
Community
  • 1
  • 1
pomber
  • 23,132
  • 10
  • 81
  • 94
  • 4
    Unfortunately the documentation for [UIEvent.initUIEvent()](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/initUIEvent) says `Do not use this method anymore as it is deprecated.` The [createEvent docs](https://developer.mozilla.org/en-US/docs/Web/API/Document/createEvent#Notes) say "Many methods used with createEvent, such as initCustomEvent, are deprecated. Use [event constructors](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) instead." [This page](https://developer.mozilla.org/en-US/docs/Web/API/UIEvent) looks promising for UI events. – Racing Tadpole Dec 03 '15 at 05: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](http://stackoverflow.com/a/18693617/264628). – BrianS Jan 19 '16 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 – Dinesh Gopal Chand Feb 15 '19 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');
BBQ Singular
  • 457
  • 4
  • 15
9

just

$(window).resize();

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

Matt Sich
  • 3,905
  • 1
  • 22
  • 26
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);
webaholik
  • 1,619
  • 1
  • 19
  • 30
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.

Pooyan Khosravi
  • 4,861
  • 1
  • 19
  • 20
T.O.
  • 39
  • 3
    Why is this marked down? Is it incorrect? Is it browser dependent? – Peter Wone May 04 '14 at 04:08
  • 3
    This doesn't work in **any** browser: Chrome, Firefox, IE, Firefox tested. – fregante Sep 25 '15 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 '16 at 09:04
  • Both resizeBy() and resizeTo() are working fine in latest stable Chrome ver. 76.0 – VanagaS Sep 21 '19 at 12:33