Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 781
Ralph David Abernathy Avatar asked Mar 13 '23 01:03

Ralph David Abernathy


1 Answers

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.

like image 61
Ted Morin Avatar answered Apr 27 '23 03:04

Ted Morin