9

I am trying to fire the resize event on window programmatically:

var evt = document.createEvent('HTMLEvents');
evt.initEvent('resize', true, false);
window.dispatchEvent(evt);

That unfortunately does not work. I am trying to make ExtJS library to do recalculations, and it uses DOM Level 3 events so I cannot just call window.onresize();.

Tower
  • 98,741
  • 129
  • 357
  • 507

3 Answers3

27

You are creating the wrong event.

Resize is a UIEvent, read the specs here

You need to do this:

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

See it in action here: http://jsfiddle.net/9hsBA/

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
  • That seems to work on JSFiddle, but when I run it in WebKit Inspector console, ExtJS application does not layout. Nothing happens. It layouts if I resize the browser window manually. – Tower Oct 01 '11 at 19:00
  • In that case ExtJS does not use DOM level 3 events like you stated, but since i don't know ExtJS i have no idea how their implementation is. – Martin Jespersen Oct 01 '11 at 19:05
  • I've been looking for this solution for a while and to understand why resize() wasn't working. Thank you very much indeed. – jtromans Sep 20 '13 at 10:27
4

In case createEvent might get deprecated in favor of CustomEvent, here's a similar snippet using the CustomEvent API:

var ev = new CustomEvent('resize'); //instantiate the resize event
ev.initEvent('resize');

window.dispatchEvent(ev); // fire 'resize' event!
yuvilio
  • 3,795
  • 32
  • 35
3

Just in case anyone else needs this, in Extjs 4.1 you can do something typically inelegant...

    Ext.ComponentQuery.query('viewport')[0].doLayout();

No need for an id on the viewport - the .query('viewport') part is using the viewport's alias config.

PilotGuru
  • 51
  • 1