How to trigger the window resize event in JavaScript?
Asked Answered
D

10

434

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?

Dixon answered 30/11, 2009 at 8:16 Comment(0)
B
491

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);
}
Beset answered 30/11, 2009 at 8:26 Comment(6)
Your anonymous function is unnecessary. window.onresize = doALoadOfStuff; Also, this doesn't answer the question, pinouchon's answer below is the correct answer.Floreated
To Googler's: Have a look at @avetisk's answer.Lacuna
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.Zachariah
@Zachariah - then my last example is better in your case.Beset
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'."Jook
much obliged mate. this was really helpfullGuidotti
F
845
window.dispatchEvent(new Event('resize'));
Falgout answered 9/9, 2013 at 7:45 Comment(15)
seems to work with Chrome, FF, Safari, but not: IE !Pent
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.Mcclary
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)Rheometer
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);Laudation
Victor && @Manfred: please specify for which version of which browser(s), I'll quote your comments in my answer.Falgout
It fails with "Object doesn't support this action" in my IE11Quiz
Try Manfred's solution @pomber. It is the only one that worked for me for IE Edge and may work for IE11 as well.Croissant
Thanks @RobertWaddell, actually I've already done that and posted it as an answer hereQuiz
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.Interleaf
Anyidea why jquery $(window).trigger('resize') not working?Refit
this worked good for me, better than $(window).trigger('resize')Godparent
Just to add, this did work for me but the jQuery version $(window).trigger('resize') did not. jQuery must do something slightly different.Theta
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 sameLactary
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.Hayleyhayloft
'evt.initUIEvent' is deprecated as it is written in above comment by @LaudationBrodeur
B
491

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);
}
Beset answered 30/11, 2009 at 8:26 Comment(6)
Your anonymous function is unnecessary. window.onresize = doALoadOfStuff; Also, this doesn't answer the question, pinouchon's answer below is the correct answer.Floreated
To Googler's: Have a look at @avetisk's answer.Lacuna
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.Zachariah
@Zachariah - then my last example is better in your case.Beset
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'."Jook
much obliged mate. this was really helpfullGuidotti
T
160

With jQuery, you can try to call trigger:

$(window).trigger('resize');
Teodor answered 12/4, 2013 at 12:54 Comment(6)
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.Sebaceous
No need for JQuery indeed but I prefer JQuery solution as my product uses JQuery extensively.Wallache
Where would this be added to resize a wordpress page after it has loaded?Vivisect
This is not working for me in latest Chrome, this answer does: https://mcmap.net/q/41595/-how-to-trigger-the-window-resize-event-in-javascriptOverlooker
Sometime I use window.dispatchEvent to trigger event, but it didn't work.But jquery's trigger still work. So nice with jquery.Salim
this is what I initially tried- it didn't work, but window.dispatchEvent(new Event('resize')); didBashuk
S
73

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);
}
Spiros answered 8/5, 2017 at 11:43 Comment(2)
This is a good way to do it across browsers without using jQuery.Biafra
no idea why this isn't the top answer......this is better than the "either or" answers that are accepted....Kanter
Q
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);
});
Quiz answered 9/8, 2015 at 0:58 Comment(3)
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.Spectroscopy
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.Lupitalupo
@Quiz Thanks for the solution, Actually I was trying to trigger custom event for window resize to resize my chart... your solution save my dayCircumstance
C
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');
Cornelison answered 25/3, 2014 at 14:59 Comment(1)
Works in Chrome today.Overlooker
U
9

just

$(window).resize();

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

Underslung answered 18/12, 2014 at 1:19 Comment(1)
And even if you have jQuery, it only triggers events that were bound with jQuery.Aldarcy
O
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);
Overlooker answered 14/8, 2019 at 22:20 Comment(2)
Works great in Chrome and FF, but didn't work in IE11Fioritura
@Fioritura - 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.Overlooker
P
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" >..
Plantation answered 19/7, 2019 at 22:13 Comment(0)
L
-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.

Leptophyllous answered 23/3, 2014 at 15:32 Comment(4)
Why is this marked down? Is it incorrect? Is it browser dependent?Hydrochloride
This doesn't work in any browser: Chrome, Firefox, IE, Firefox tested.Faeroese
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.Hilariahilario
Both resizeBy() and resizeTo() are working fine in latest stable Chrome ver. 76.0Shelby

© 2022 - 2024 — McMap. All rights reserved.