242

What is the correct (modern) method for tapping into the window resize event that works in Firefox, WebKit, and Internet Explorer?

And can you turn both scrollbars on/off?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BuddyJoe
  • 69,735
  • 114
  • 291
  • 466
  • I'm also looking into this. I'd like to try to apply the solutions offered here, but I'm afraid I don't understand the syntax: $(window). Is that something specific to jquery? – Byff Feb 15 '11 at 23:59
  • 1
    Byff, yes, $(window) is a jQuery construct. window.onresize is the equivalent in raw JavaScript. – Andrew Hedges Mar 25 '11 at 06:11
  • This demo may help anybody to test on all browsers http://jsfiddle.net/subodhghulaxe/bHQV5/2/ – Subodh Ghulaxe Apr 06 '13 at 11:20
  • `window.dispatchEvent(new Event('resize'));` http://stackoverflow.com/questions/1818474/how-to-trigger-the-window-resize-event-in-javascript#18693617 – Dylan Valade May 25 '16 at 14:03
  • On Opera on mobile it is triggered each time top bar (browser UI) is showing/hiding. – psur Aug 04 '18 at 06:56

11 Answers11

370

jQuery has a built-in method for this:

$(window).resize(function () { /* do something */ });

For the sake of UI responsiveness, you might consider using a setTimeout to call your code only after some number of milliseconds, as shown in the following example, inspired by this:

function doSomething() {
    alert("I'm done resizing for the moment");
};

var resizeTimer;
$(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(doSomething, 100);
});
Andrew Hedges
  • 21,688
  • 16
  • 67
  • 79
  • 34
    Why this event is not fired when window is expanded to full screen with button? – Sly Aug 31 '11 at 14:14
  • 2
    @Sly For me it works,in Safari, Chrome and Mozilla on Mac. Which browser do you use? – Mark Vital Oct 25 '12 at 20:40
  • 2
    @Sly: `$('.button').on({ click: function(){ /* your code */ $(window).trigger('resize') })` – Zack Zatkin-Gold Jan 07 '13 at 20:29
  • 1
    Also of note is that if you call a named function just type the name, don't quote it or put parentheses if there are no arguments to pass to it.) – Elijah Lynn Mar 13 '13 at 20:02
  • 6
    Elijah, this is JavaScript. What you wrote is not correct (except for one specific case when you are constructing with new). – Yoh Suzuki Mar 13 '13 at 21:00
  • 1
    Considering most need the optimized version for UI responsiveness, it would be nice if jQuery added a second parameter, being a delay (in millis) which would automatically add the 'responsiveness' logic as proposed above. – Jeach Mar 19 '13 at 18:08
  • 2
    See [my answer](http://stackoverflow.com/a/18745301/895558) below if you don't want to use jQuery. – Jondlm May 15 '14 at 20:32
  • I had a issue in Firefox saying that $ is not defined when the resize event was fired. I've put my resize function inside a setTimeout and it worked now! – Alexandru Trandafir Catalin May 18 '15 at 11:55
  • 3
    It's worth mentioning that this jQuery function "adds" a function call to the current list of functions that should be called on a window resize. It does not overwrite existing events that are currently scheduled on a window resize. – RTF May 26 '15 at 19:27
49
$(window).bind('resize', function () { 

    alert('resize');

});
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
fts
  • 491
  • 4
  • 2
  • 4
    I prefer the bind approach, since the resize() method is actually actually a shortcut for the full bind approach, and I often find that there is usually more than one event handler I *should* be applying to an element. – Mike Kormendy Sep 10 '12 at 02:47
  • @Mike - Not only that, but I'm guessing the resize method has no "unbind" method in the event you want to remove the listener. "bind" is definitely the way to go! – Shane May 01 '13 at 13:26
44

Here is the non-jQuery way of tapping into the resize event:

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

It works on all modern browsers. It does not throttle anything for you. Here is an example of it in action.

Jondlm
  • 8,764
  • 2
  • 24
  • 30
  • this solution wouldn't be working in IE. Fixed version with support of IE dom: http://stackoverflow.com/questions/6927637/addeventlistener-in-internet-explorer – Sergey Mar 28 '16 at 10:38
  • 1
    > It does not throttle anything for you. Could you please elaborate? What should/would it throttle? Does it relate to the event firing many times in a row? – josinalvo Jul 11 '17 at 20:09
  • @josinalvo generally when you're listening to an event that fires _a lot_ you'll want to [debounce (e.g. lodash)](https://lodash.com/docs/4.17.4#debounce) it so you don't cause a bottleneck in your program. – Jondlm Jul 11 '17 at 21:51
17

Sorry to bring up an old thread, but if someone doesn't want to use jQuery you can use this:

function foo(){....};
window.onresize=foo;
Community
  • 1
  • 1
  • 8
    Just be aware that this will clobber any existing handlers that may be bound to window.onresize. If your script has to live an an ecosystem with other scripts, you shouldn't assume your script is the only one to want to do something on window resize. If you can't use a framework such as jQuery, you should at least consider grabbing the existing window.onresize, and adding your handler to the end of it, rather than completely clobbering it. – Tom Auger Aug 22 '13 at 15:28
  • 2
    @TomAuger *"you should at least consider grabbing the existing window.onresize, and adding your handler to the end of it"* - you probably meant the opposite, i.e. "to call existing handler at the end of your handler"? I would really like to see a javascript code that would add something to the end of already existing function :-) – Tomas Mar 06 '14 at 09:39
  • I see your point, in a sense - your new onResize handler needs to wrap the existing onResize. However, it doesn't have to call the function you wanted to add to onResize until after it has called the original onResize handler. So you can still make sure your new onResize function executes after the original onResize function, which is probably better than the reverse. – Tom Auger Mar 06 '14 at 23:01
8

Since you are open to jQuery, this plugin seems to do the trick.

Liam Laverty
  • 152
  • 2
  • 9
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
5

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):

// did not work in IE10
$(function() {
    $(window).resize(CmsContent.adjustSize);
});

while this worked in both browsers:

// did work in IE10
$(function() {
    $(window).bind('resize', function() {
        CmsContent.adjustSize();
    };
});

Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.

bassim
  • 886
  • 1
  • 21
  • 33
  • 1
    There's two changes. Which one had the effect? (`.resize()` to `.bind('resize')` or adding the anonymous function? I'm thinking it's the second.) – WraithKenny May 16 '14 at 21:29
  • @WraithKenny Good point. It very well may be that adding the anonymous function was what made it work. I don't recall if I tried it. – bassim May 26 '14 at 09:17
  • 1
    In the first case, the `adjustSize` method loses its context of `this`, whereas the second call `CmsContent.adjustSize()` preserves `this`, i.e. `this === CmsContent`. If the `CmsContent` instance is required in the `adjustSize` method, then the first case will fail. Second case will work for every kind of function call, so it's recommended to always pass an anonymous function. – Henry Blyth Sep 22 '17 at 13:35
  • 1
    @HenryBlyth Thank you! +1 – bassim Oct 06 '17 at 10:19
4

jQuery provides $(window).resize() function by default:

<script type="text/javascript">
// function for resize of div/span elements
var $window = $( window ),
    $rightPanelData = $( '.rightPanelData' )
    $leftPanelData = $( '.leftPanelData' );

//jQuery window resize call/event
$window.resize(function resizeScreen() {
    // console.log('window is resizing');

    // here I am resizing my div class height
    $rightPanelData.css( 'height', $window.height() - 166 );
    $leftPanelData.css ( 'height', $window.height() - 236 );
});
</script> 
Paul Schreiber
  • 12,531
  • 4
  • 41
  • 63
Aditya P Bhatt
  • 21,431
  • 18
  • 85
  • 104
3

I consider the jQuery plugin "jQuery resize event" to be the best solution for this as it takes care of throttling the event so that it works the same across all browsers. It's similar to Andrews answer but better since you can hook the resize event to specific elements/selectors as well as the entire window. It opens up new possibilities to write clean code.

The plugin is available here

There are performance issues if you add a lot of listeners, but for most usage cases it's perfect.

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
oldwizard
  • 5,012
  • 2
  • 31
  • 32
0

I think you should add further control to this:

    var disableRes = false;
    var refreshWindow = function() {
        disableRes = false;
        location.reload();
    }
    var resizeTimer;
    if (disableRes == false) {
        jQuery(window).resize(function() {
            disableRes = true;
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(refreshWindow, 1000);
        });
    }
Francesco Frapporti
  • 5,195
  • 4
  • 32
  • 39
0

hope it will help in jQuery

define a function first, if there is an existing function skip to next step.

 function someFun() {
 //use your code
 }

browser resize use like these.

 $(window).on('resize', function () {
    someFun();  //call your function.
 });
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Venu immadi
  • 1,585
  • 11
  • 20
0

Besides the window resize functions mentioned it is important to understand that the resize events fire a lot if used without a deboucing the events.

Paul Irish has an excellent function that debounces the resize calls a great deal. Very recommended to use. Works cross-browser. Tested it in IE8 the other day and all was fine.

http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/

Make sure to check out the demo to see the difference.

Here is the function for completeness.

(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
  // smartresize 
  jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');


// usage:
$(window).smartresize(function(){
  // code that takes it easy...
});
lowtechsun
  • 1,915
  • 5
  • 27
  • 55