Ralph David Abernathy
Ralph David Abernathy

Reputation: 5518

Detect when browser window has been resized from certain size to a larger size?

I want to reset a particular element once the browser window has been resized from any size less than 641px, to a greater size. Here is an example of what I am trying to achieve, written in pseudo code:

if (browser.window <= 641px && browser.window.resizedTo > 641px) {
  $( ".foo" ).removeClass( "bar" )
}

Thank you!

Upvotes: 5

Views: 4836

Answers (2)

Ted Morin
Ted Morin

Reputation: 668

I'll assume for the sake of this question that you mean 641px as the width, but I left the innerHeight variable there, too, in case you need it:

// Closure last-height/width
var lastX = window.innerWidth
var lastY = window.innerHeight

function fooOnResize() {
   var x = window.innerWidth
   var y = window.innerHeight
   if (lastX <= 641 && 641 < x) {
      $(".foo").removeClass("bar")
   }
   lastX = x
   lastY = y
}

window.addEventListener("resize", fooOnResize)
// Also okay: window.onresize = fooOnResize

The trick is to basically hold the last size in some closure variables, then on resize, you can make your comparison. After you have done the comparison and the work, you store the current x/y as the last ones, for the next resize.

Upvotes: 7

Nathan Friend
Nathan Friend

Reputation: 12834

Try the window.onresize event:

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onresize

You can get the current dimensions of the browser window using window.innerHeight and window.innerWidth:

window.onresize = function() {
    console.log('height: ' + window.innerHeight);
    console.log('width: ' + window.innerWidth);
}

Upvotes: 1

Related Questions