Detect a window width change but not a height change

I'm using the .resize() function to detect window re-size events, but this detects both height and width changes.

Is there any way to detect just a width change and not a height change?


var width = $(window).width();
$(window).on('resize', function() {
  if ($(this).width() !== width) {
    width = $(this).width();
    console.log(width);
  }
});

you can detect both events and just execute code when it's a width change:

var lastWidth = $(window).width();

$(window).resize(function(){
   if($(window).width()!=lastWidth){
      //execute code here.
      lastWidth = $(window).width();
   }
})        

And you might want to check event debouncing.

Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called.


Read more:


  • https://css-tricks.com/the-difference-between-throttling-and-debouncing/
  • https://davidwalsh.name/javascript-debounce-function

Even though there are already a couple of answers with working solutions, this kind of task is performance critical (window resize event is triggered many times while a user is resizing the window) so I strongly suggest you to take care of the performance. Please, have a look at the optimized code below:

/* Do not waste time by creating jQuery object from window multiple times.
 * Do it just once and store it in a variable. */
var $window = $(window);
var lastWindowWidth = $window.width();

$window.resize(function () {
    /* Do not calculate the new window width twice.
     * Do it just once and store it in a variable. */
    var windowWidth = $window.width();

    /* Use !== operator instead of !=. */
    if (lastWindowWidth !== windowWidth) {
        // EXECUTE YOUR CODE HERE
        lastWindowWidth = windowWidth;
    }
});

Plus, you might be interested in checking the Debounce / Throttle patterns - they improve performance enormously in cases like this.


One can also use this tiny jQuery plugin for this: https://github.com/adjohnson916/jquery-resize-dimension

Keeps your own code more readable:

ResizeDimension.bind('width');
$(window).on('resize-width', function () {
  console.log('resize-width event');
});

or just:

$(window).resizeDimension('width', function () {
  console.log('resize-width event');
});