tags:

views:

20426

answers:

5

How can I hook into a browser window resize event? I see there's a jQuery way of doing it but I would prefer not to bring this into my project for just this one requirement.

http://stackoverflow.com/questions/599288/cross-browser-window-resize-event-javascript-jquery

+11  A: 

jQuery is just wrapping the standard resize DOM event, eg.

window.onresize = function(event) {
    ...
}

jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but i'm not sure if any of the browsers differ, but i'd encourage you to test in Firefox, Safari, and IE

olliej
I'm not sure how much work they do on the consistency. In Firefox the event gets called as long as your resizing (it loops) in IE(6?) it will only fire when your done resizing.
Pim Jager
There's also the blog that lakshmanaraj refers to :-/
olliej
+3  A: 

The following May be useful to you.

http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html

lakshmanaraj
+4  A: 
window.onresize = function() {
//your code

}
saravanakumar
+1  A: 

Thanks for referencing my blog post at http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html.

While you can just hook up to the standard window resize event, you'll find that in IE, the event is fired once for every X and once for every Y axis movement, resulting in a ton of events being fired which might have a performance impact on your site if rendering is an intensive task.

My method involves a short timeout that gets cancelled on subsequent events so that the event doesn't get bubbled up to your code until the user has finished resizing the window.

Steven Berkovitz
+3  A: 

Use this add Events in both IE and Firefox:

var addEvent = function(elem, type, eventHandle) {
    if (elem == null || elem == undefined) return;
    if ( elem.addEventListener ) {
        elem.addEventListener( type, eventHandle, false );
    } else if ( elem.attachEvent ) {
        elem.attachEvent( "on" + type, eventHandle );
    }
};

Then simply add your event listener to the window:

addEvent(window, "resize", function() { alert("hello there!"); } );
Alex V