Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM event fired by window resize

I have a page that has a fairly complicated layout. When the page is initially opened there's a problem with the aligment of some of the elements. However, this problem can be resolved (permanently) by changing the size of the brower window.

Obviously I don't want the user to have to resize the browser window in order for the page to display correctly, so I'm wondering if there's a way I can programatically trigger the handlers attached to the browser's resize event when the page first loads?

Update

I found out that the following code will fire any handlers attached to the window's resize event:

if (document.createEvent) { // W3C
    var ev = document.createEvent('Event');
    ev.initEvent('resize', true, true);
    window.dispatchEvent(ev);
} else { // IE
    document.fireEvent('onresize');
}

I verified that this does indeed trigger the window's resize event handlers, but when I run this code in the Firebug console, it doesn't fix the layout problem.

So it seems that the code which fixes the layout when the browser is resized is not a handler of the window's resize event, but a handler of something else. How can I go about tracking down which event handler I need to fire?

Is it possible that when the browser is manually resized, the resize event propogates down to all the children of window, but when the code above is executed, the resize handler only fires on window itself?

like image 649
Dónal Avatar asked Jan 03 '12 12:01

Dónal


People also ask

How do you fire a window resize event?

In your modern browsers, you can trigger the event using: window. dispatchEvent(new Event('resize'));

What happens when window is resized?

The resize event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register resize event handlers on any HTML element.

How do I resize a window?

Click and drag the window at any of the window borders until it's at the desired size.


1 Answers

For IE compatibility

function fireResize(){
    if (document.createEvent) { // W3C
        var ev = document.createEvent('Event');
        ev.initEvent('resize', true, true);
        window.dispatchEvent(ev);
    }
    else { // IE
        element=document.documentElement;
        var event=document.createEventObject();
        element.fireEvent("onresize",event);
    }
};
fireResize();
like image 174
Slava Jinjikhashvilli Avatar answered Oct 11 '22 20:10

Slava Jinjikhashvilli