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?

5
  • 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, 2011 at 23:59
  • 1
    Byff, yes, $(window) is a jQuery construct. window.onresize is the equivalent in raw JavaScript. Mar 25, 2011 at 6:11
  • This demo may help anybody to test on all browsers jsfiddle.net/subodhghulaxe/bHQV5/2 Apr 6, 2013 at 11:20
  • window.dispatchEvent(new Event('resize')); stackoverflow.com/questions/1818474/… May 25, 2016 at 14:03
  • On Opera on mobile it is triggered each time top bar (browser UI) is showing/hiding.
    – psur
    Aug 4, 2018 at 6:56

11 Answers 11

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);
});
9
  • 34
    Why this event is not fired when window is expanded to full screen with button?
    – Sly
    Aug 31, 2011 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, 2012 at 20:40
  • 2
    @Sly: $('.button').on({ click: function(){ /* your code */ $(window).trigger('resize') }) Jan 7, 2013 at 20:29
  • 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, 2013 at 21:00
  • 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, 2015 at 19:27
49
$(window).bind('resize', function () { 

    alert('resize');

});
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. Sep 10, 2012 at 2: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 1, 2013 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.

3
  • this solution wouldn't be working in IE. Fixed version with support of IE dom: stackoverflow.com/questions/6927637/…
    – Sergey
    Mar 28, 2016 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, 2017 at 20:09
  • @josinalvo generally when you're listening to an event that fires a lot you'll want to debounce (e.g. lodash) it so you don't cause a bottleneck in your program.
    – Jondlm
    Jul 11, 2017 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;
3
  • 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, 2013 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 6, 2014 at 9: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 6, 2014 at 23:01
8

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

0
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.

4
  • 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.) May 16, 2014 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, 2014 at 9: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. Sep 22, 2017 at 13:35
  • 1
    @HenryBlyth Thank you! +1
    – bassim
    Oct 6, 2017 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> 
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.

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);
        });
    }
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.
 });
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...
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.