442

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

863
window.dispatchEvent(new Event('resize'));
Sign up to request clarification or add additional context in comments.

9 Comments

seems to work with Chrome, FF, Safari, but not: IE !
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.
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)
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);
It fails with "Object doesn't support this action" in my IE11
|
497

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);
}

5 Comments

Your anonymous function is unnecessary. window.onresize = doALoadOfStuff; Also, this doesn't answer the question, pinouchon's answer below is the correct answer.
To Googler's: Have a look at @avetisk's answer.
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 - then my last example is better in your case.
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'."
159

With jQuery, you can try to call trigger:

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

3 Comments

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.
No need for JQuery indeed but I prefer JQuery solution as my product uses JQuery extensively.
Where would this be added to resize a wordpress page after it has loaded?
75

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);
}

Comments

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);
});

2 Comments

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.
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.
16

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');

Comments

9

just

$(window).resize();

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

1 Comment

And even if you have jQuery, it only triggers events that were bound with jQuery.
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 Comments

Works great in Chrome and FF, but didn't work in IE11
@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.
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" >..

Comments

-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 Comments

Why is this marked down? Is it incorrect? Is it browser dependent?
This doesn't work in any browser: Chrome, Firefox, IE, Firefox tested.
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.
Both resizeBy() and resizeTo() are working fine in latest stable Chrome ver. 76.0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.