644

How can I hook into a browser window resize event?

There's a jQuery way of listening for resize events but I would prefer not to bring it into my project for just this one requirement.

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
Dead account
  • 18,306
  • 13
  • 48
  • 79

13 Answers13

670

Best practice is to attach to the resize event.

window.addEventListener('resize', function(event) {
    ...
}, true);

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
  • 32,789
  • 8
  • 55
  • 54
  • 1
    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 Mar 13 '09 at 09:25
  • 231
    One potential gotcha with this method is that you're overriding the event and so you can't attach multiple actions to an event. The addEventListener/attachEvent combo is the best way to go to make your javascript play friendly with any other script that might be executing on the page. – MyItchyChin Jun 21 '11 at 20:20
  • 4
    var onresize = window.onresize; window.onresize = function(event) { if (typeof onresize === 'function') onresize(); /** ... */ } – SubOne Jul 17 '12 at 00:58
  • Nice one @MyItchyChin I used: $(window).on('resize', function (e) { console.log('message 1'); }); – Mark Robson Jun 21 '13 at 10:23
  • Check out the jQuery commented source, there's a lot of good stuff there. – dalgard Sep 06 '13 at 15:08
  • 246
    `window.addEventListener('resize', function(){}, true);` – WebWanderer Nov 07 '14 at 16:57
  • 18
    @SubOne a perfect example of how one should never do it. – Eugene Pankov Feb 10 '16 at 16:58
  • 1
    This is not the way to do this. Hasn't been for a long time. Use `addEventListener` instead so your script doesn't break other scripts on the page. – Stijn de Witt Jun 19 '16 at 14:14
  • 32
    **ECMAScript 6**: `window.onresize = () => { /* code */ };` or better: `window.addEventListener('resize', () => { /* code */ });` – Derk Jan Speelman Jul 12 '17 at 21:54
  • An possible typo could be **document**.addEventListener('resize' ...); **is not document, is window**, then **window**.addEventListener('resize' ...); is the way. – Máxima Alekz Feb 06 '19 at 15:29
  • Overwriting a window function is never a good idea. Use eventListeners for that. – jbartolome Jun 19 '19 at 19:50
603

First off, I know the addEventListener method has been mentioned in the comments above, but I didn't see any code. Since it's the preferred approach, here it is:

window.addEventListener('resize', function(event){
  // do stuff here
});

Here's a working sample.

Jondlm
  • 8,264
  • 2
  • 20
  • 30
  • 69
    This is the most straightforward answer. – jacoviza Apr 09 '14 at 17:49
  • 7
    Sounds like the best answer because your not overwriting the window.onresize event :-) – James Harrington May 08 '15 at 14:53
  • 31
    Many people add anonymous event listeners like you do in this example, but it is not really good practice, because this approach makes it [impossible](https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Registration-interfaces) to remove these listeners later. This used to be no problem because web pages were short-lived anyway, but in this day and age of AJAX and RIAs and SPAs it's becoming one. We need a way to manage event listeners lifecycle. Thus, It would be better to factor out the listener function into a separate function so it can be removed later with `removeEventListener`. – Stijn de Witt Jun 19 '16 at 14:30
  • 8
    why can't everyone answer like this without all the fluff – quemeful Aug 19 '17 at 17:59
  • alright... this seems more legit for a correct answer – jet_choong Mar 12 '18 at 07:55
  • Choose this one but edit it to say `window.addEventListener('resize', onResize)` and add `window.removeEventListener('resize', onResize)` like @StijndeWitt suggested. – ThaJay May 14 '18 at 11:25
  • 2
    I think there is truth to both Stijn de Witt's and quemeful's answers here. Sometimes you care about removing event listeners, but in the case that you don't, adding all that extra code like in the example above is unnecessary and can both to bloat and less readability. In my opinion, if you don't envision a reason to need to remove the listener, this approach is the best solution. You can always rewrite it later if necessary. In my experience, these needs only arise in specific situations. – cazort Feb 22 '19 at 15:57
531

Never override the window.onresize function.

Instead, create a function to add an Event Listener to the object or element. This checks and incase the listeners don't work, then it overrides the object's function as a last resort. This is the preferred method used in libraries such as jQuery.

object: the element or window object
type: resize, scroll (event type)
callback: the function reference

var addEvent = function(object, type, callback) {
    if (object == null || typeof(object) == 'undefined') return;
    if (object.addEventListener) {
        object.addEventListener(type, callback, false);
    } else if (object.attachEvent) {
        object.attachEvent("on" + type, callback);
    } else {
        object["on"+type] = callback;
    }
};

Then use is like this:

addEvent(window, "resize", function_reference);

or with an anonymous function:

addEvent(window, "resize", function(event) {
  console.log('resized');
});
Alex V
  • 17,468
  • 5
  • 32
  • 34
  • 103
    This should have been the accepted answer. Overriding onresize is just bad practice. – Tiberiu-Ionuț Stan Jun 11 '12 at 10:05
  • 10
    hah, what's with all the extra null checks? trying to work in IE 4.5 or something? – FlavorScape Sep 15 '12 at 04:24
  • @FlavorScape Late answer: You can specify if you want your page to be *zoomable/resizable* on mobile devices there days. So adding a function for that purpose when it'll never be triggered would be stupid. – Jeff Noel Jul 15 '13 at 14:24
  • 2
    And you are wondering how do I call this function to receive window resize events? Here is how: addEvent(window, "resize", function_reference); :) – oabarca Feb 20 '14 at 17:28
  • 6
    Note that as of IE 11, `attachEvent` is no longer supported. The preferred way for the future is `addEventListener`. – Luke Feb 26 '14 at 23:26
  • 6
    Be careful with `elem == undefined`. It is possible (although unlikely) that "undefined" is locally defined as something else. http://stackoverflow.com/questions/8175673/jslint-complains-about-redefining-undefined – Luke Feb 26 '14 at 23:39
  • 1
    ironic when you just did... twice. – Alex V Oct 04 '15 at 05:22
  • Why doesn't your `addEvent` function allow for the return of the `event` object. In your example, your anonymous function is expecting the `event` object, while the `addEventListener` method you use within `addEvent` does not return it. You should add a parameter: `addEvent = function(object, type, callback, **eventReturn**)` and use this new parameter in your `addEventListenerCall`: `object.addEventListener(type, callback, **eventReturn**);` – WebWanderer Oct 05 '15 at 18:15
  • You should also avoid using the JavaScript reserved word `object` as a variable name. The function you have provided will not work in strict mode. I would suggest changing the parameter `object` of your `addEvent` function to "obj" instead. – WebWanderer Oct 05 '15 at 18:16
  • I have provided an updated version of your function as another answer. My version includes the fixes I spoke of. – WebWanderer Oct 05 '15 at 18:40
  • 1
    `object` is not a reserved keyword. `Object` on the other hand is a built in function, so its still save to use. – Alex V Oct 06 '15 at 05:35
  • 1
    Peter-Paul Koch from Quirksmode once held a [competetion](http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html) for who could write the best `addEvent` implementation. To be honest, I wouldn't use it anymore. Just use `addEventListener`. The few legacy browsers that did not support it have been [laid to rest](https://www.microsoft.com/en-us/WindowsForBusiness/End-of-IE-support) and support is now pretty much [universal](http://caniuse.com/#feat=addeventlistener). – Stijn de Witt Jun 19 '16 at 14:19
  • @Luke I recently had a problem with an api that returned "undefined" and it confused me for days. – Daniel Vestøl Jul 17 '17 at 17:42
  • 1
    Never is a really strong word. Especially in programming. If you are writing small scripts to implement a specific need, do whatever you want. – quemeful Aug 19 '17 at 17:58
  • 1
    This `addEvent` function is perfect. It guarantees that you can never remove that event listener afterwards. And with hundreds of upvotes, it must be the right thing to do:-) – Drenai Jan 10 '18 at 22:00
  • Just before the `object["on"+type] = callback;` statement, shouldn't you `const previousCallback = object["on"+type] || () => {};` then set `object["on"+type] = () => { previousCallback(); callback(); }`? May want to be mindful of avoiding arrow functions incase use of the `this` keyword is being used.. – Steven Dec 23 '20 at 02:36
43

The resize event should never be used directly as it is fired continuously as we resize.

Use a debounce function to mitigate the excess calls.

window.addEventListener('resize',debounce(handler, delay, immediate),false);

Here's a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.

const debounce = (func, wait, immediate) => {
    var timeout;
    return () => {
        const context = this, args = arguments;
        const later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

This can be used like so...

window.addEventListener('resize', debounce(() => console.log('hello'),
200, false), false);

It will never fire more than once every 200ms.

For mobile orientation changes use:

window.addEventListener('orientationchange', () => console.log('hello'), false);

Here's a small library I put together to take care of this neatly.

frontsideup
  • 2,679
  • 1
  • 19
  • 22
  • I appreciate the information on: debounce (it now seems an invaluable concept/function even though I previously resisted using timeouts in this way), lodash (though I'm personally not convinced) and resolving the ambiguity about whether to use addEvent as a fallback to addEventListener (only because older answers don't really explicitly address the comments regarding this) – wunth Aug 14 '17 at 00:03
  • 5
    FYI since you are using ES6 arrow func notation, the inner function needs to have `(...arguments) => {...}` (or `...args` for less confusion) as the `arguments` variable is no longer available their scope. – coderatchet Sep 04 '17 at 03:43
  • I'm fully aware, that snippet is not my code, it's just as an example. – frontsideup Sep 15 '17 at 18:06
  • Great answer, the perf issues with resize need to be addressed! Debouncing is an option, another is simple throttling (which might be the way to go if you need your UI to resize in "steps"). See http://bencentra.com/code/2015/02/27/optimizing-window-resize.html for examples – Robin Métral Oct 14 '19 at 12:20
35

Solution for 2018+:

You should use ResizeObserver. It is a browser-native solution that has a much better performance than to use the resize event. In addition, it not only supports the event on the document but also on arbitrary elements.

var ro = new ResizeObserver( entries => {
  for (let entry of entries) {
    const cr = entry.contentRect;
    console.log('Element:', entry.target);
    console.log(`Element size: ${cr.width}px x ${cr.height}px`);
    console.log(`Element padding: ${cr.top}px ; ${cr.left}px`);
  }
});

// Observe one or multiple elements
ro.observe(someElement);

Currently, Firefox, Chrome, Safari, and Edge support it. For other (and older) browsers you have to use a polyfill.

str
  • 33,096
  • 11
  • 88
  • 115
16

I do believe that the correct answer has already been provided by @Alex V, yet the answer does require some modernization as it is over five years old now.

There are two main issues:

  1. Never use object as a parameter name. It is a reservered word. With this being said, @Alex V's provided function will not work in strict mode.

  2. The addEvent function provided by @Alex V does not return the event object if the addEventListener method is used. Another parameter should be added to the addEvent function to allow for this.

NOTE: The new parameter to addEvent has been made optional so that migrating to this new function version will not break any previous calls to this function. All legacy uses will be supported.

Here is the updated addEvent function with these changes:

/*
    function: addEvent

    @param: obj         (Object)(Required)

        -   The object which you wish
            to attach your event to.

    @param: type        (String)(Required)

        -   The type of event you
            wish to establish.

    @param: callback    (Function)(Required)

        -   The method you wish
            to be called by your
            event listener.

    @param: eventReturn (Boolean)(Optional)

        -   Whether you want the
            event object returned
            to your callback method.
*/
var addEvent = function(obj, type, callback, eventReturn)
{
    if(obj == null || typeof obj === 'undefined')
        return;

    if(obj.addEventListener)
        obj.addEventListener(type, callback, eventReturn ? true : false);
    else if(obj.attachEvent)
        obj.attachEvent("on" + type, callback);
    else
        obj["on" + type] = callback;
};

An example call to the new addEvent function:

var watch = function(evt)
{
    /*
        Older browser versions may return evt.srcElement
        Newer browser versions should return evt.currentTarget
    */
    var dimensions = {
        height: (evt.srcElement || evt.currentTarget).innerHeight,
        width: (evt.srcElement || evt.currentTarget).innerWidth
    };
};

addEvent(window, 'resize', watch, true);
WebWanderer
  • 7,827
  • 3
  • 25
  • 42
12

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
  • 773
  • 4
  • 13
7
window.onresize = function() {
    // your code
};
informatik01
  • 15,174
  • 9
  • 67
  • 100
saravanakumar
  • 191
  • 2
  • 2
  • 23
    As many of the comments above say, it's best not to overwrite the onresize function; rather add a new event. See Jondlm's answer. – Luke Feb 26 '14 at 23:20
6

The following blog post may be useful to you: Fixing the window resize event in IE

It provides this code:

Sys.Application.add_load(function(sender, args) {
    $addHandler(window, 'resize', window_resize);
});

var resizeTimeoutId;

function window_resize(e) {
     window.clearTimeout(resizeTimeoutId);
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10);
}
Rory O'Kane
  • 25,436
  • 11
  • 86
  • 123
lakshmanaraj
  • 4,102
  • 20
  • 12
3

The already mentioned solutions above will work if all you want to do is resize the window and window only. However, if you want to have the resize propagated to child elements, you will need to propagate the event yourself. Here's some example code to do it:

window.addEventListener("resize", function () {
  var recResizeElement = function (root) {
    Array.prototype.forEach.call(root.childNodes, function (el) {

      var resizeEvent = document.createEvent("HTMLEvents");
      resizeEvent.initEvent("resize", false, true);
      var propagate = el.dispatchEvent(resizeEvent);

      if (propagate)
        recResizeElement(el);
    });
  };
  recResizeElement(document.body);
});

Note that a child element can call

 event.preventDefault();

on the event object that is passed in as the first Arg of the resize event. For example:

var child1 = document.getElementById("child1");
child1.addEventListener("resize", function (event) {
  ...
  event.preventDefault();
});
rysama
  • 1,652
  • 16
  • 26
1
var EM = new events_managment();

EM.addEvent(window, 'resize', function(win,doc, event_){
    console.log('resized');
    //EM.removeEvent(win,doc, event_);
});

function events_managment(){
    this.events = {};
    this.addEvent = function(node, event_, func){
        if(node.addEventListener){
            if(event_ in this.events){
                node.addEventListener(event_, function(){
                    func(node, event_);
                    this.events[event_](win_doc, event_);
                }, true);
            }else{
                node.addEventListener(event_, function(){
                    func(node, event_);
                }, true);
            }
            this.events[event_] = func;
        }else if(node.attachEvent){

            var ie_event = 'on' + event_;
            if(ie_event in this.events){
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                    this.events[ie_event]();
                });
            }else{
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                });
            }
            this.events[ie_event] = func;
        }
    }
    this.removeEvent = function(node, event_){
        if(node.removeEventListener){
            node.removeEventListener(event_, this.events[event_], true);
            this.events[event_] = null;
            delete this.events[event_];
        }else if(node.detachEvent){
            node.detachEvent(event_, this.events[event_]);
            this.events[event_] = null;
            delete this.events[event_];
        }
    }
}
THE AMAZING
  • 1,374
  • 2
  • 15
  • 37
1
<script language="javascript">
    window.onresize = function() {
    document.getElementById('ctl00_ContentPlaceHolder1_Accordion1').style.height = '100%';
} 

</script>
Mxyk
  • 10,360
  • 16
  • 52
  • 75
0

You can use following approach which is ok for small projects

<body onresize="yourHandler(event)">

function yourHandler(e) {
  console.log('Resized:', e.target.innerWidth)
}
<body onresize="yourHandler(event)">
  Content... (resize browser to see)
</body>
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241