jQuery capture window resize snippets

Sam Deering
Share

Use jQuery capture the event of when the browser window is resized, then do something. In the example below it logs the window’s new size.

Update 16/05/2013: See the debounce method below for smarter window resizing!

//capture window resize
$(window).bind('resize', function(e)
{
    var win = $(this),
        w = win.width(),
        h = win.height();

    console.log('window resized to: ' + w + ' by ' + h);
});

//output: window resized to: 1598 by 521

Refresh page on browser resize

A pretty hacky cross browser IE8+ solution.

//this is in a timeout so it works in IE8
setTimeout(function()
{
    $(window).bind('resize', function(e)
    {
        if(window.RT) clearTimeout(window.RT);
        window.RT = setTimeout(function()
        {
            this.location.reload(false); /* false to get page from cache */
        }, 300);        
    });
}, 1000);

Example to reposition a nav bar when window is resized

Move navigation menu bar when the window is resized. Slight 300ms delay but this is to stop it from recursively calling reposition when browser is being resized.

(function($,W)
{
    //DOM Ready
    $(function()
    {
        //responsive main nav absolute top position relative to window height
        function repositionMainNav()
        {
            var newT = W.innerHeight - 300;
            newT = (newT  550) ? 550 : newT; //max top
            // console.log(newT);
            $('#navbar').css('top', newT);
        }
        repositionMainNav();

        $(W).bind('resize', function(e)
        {
            if(W.RT) clearTimeout(W.RT);
            W.RT = setTimeout(function()
            {
                //recalculate the vertical position of the main nav
                repositionMainNav();
            }, 300);
        });
    });
})(jQuery, window);

Decounced “Smarter” window resize event

Courtesy of the ever outstanding Mr Paul Irish in his debounced post and see the demo in action.

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