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

2

5

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!

Diluvial answered 3/3, 2016 at 19:12 Comment(0)
B
7

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.

Biskra answered 3/3, 2016 at 19:27 Comment(0)
G
1

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);
}
Gyrus answered 3/3, 2016 at 19:18 Comment(2)
Is there any way to detect if a browser has been resized from X to Y?Diluvial
@RalphDavidAbernathy - Not directly, but you could easily store the previous dimensions of the window and compare them with the new dimensions.Gyrus

© 2022 - 2024 — McMap. All rights reserved.