[javascript] Cross-browser window resize event - JavaScript / jQuery

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?

This question is related to javascript jquery cross-browser resize

The answer is


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> 

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;

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.


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

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.


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.


$(window).bind('resize', function () { 

    alert('resize');

});

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

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

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to cross-browser

Show datalist labels but submit the actual value Stupid error: Failed to load resource: net::ERR_CACHE_MISS Click to call html How to Detect Browser Back Button event - Cross Browser How can I make window.showmodaldialog work in chrome 37? Cross-browser custom styling for file upload button Flexbox and Internet Explorer 11 (display:flex in <html>?) browser sessionStorage. share between tabs? How to know whether refresh button or browser back button is clicked in Firefox CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

Examples related to resize

Numpy Resize/Rescale Image AngularJS $watch window resize inside directive Input type "number" won't resize How can I make all images of different height and width the same via CSS? How to get full width in body element Rerender view on browser resize with React How to resize image automatically on browser width resize but keep same height? PHPExcel auto size column width Automatically resize images with browser size using CSS Change form size at runtime in C#