Zeev Katz Zeev Katz - 1 month ago 6
Javascript Question

How to know if a screen is reduced or increased? [real time]

I'm trying to check if users reduced or increased there screens.

I have the following function and it works fine, but it relies only on the initial screen size:

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

$(function(){

$(window).resize(function(){

var resizeWidth = $(this).width();

if (resizeWidth > width) {

console.log('increased!')
width = width + 1;

} else {

console.log('reduced!')
width = width - 1;

}
});
});


Is it possible to know if the screen is increased or reduced at any time and not on the initial screen size?

Thank you all!

Answer

The window.resize that you've set up will fire continuously . Simply store the old width each time you resize and compare it to the new width, replacing the old width with the new after the comparison.

var win = $(window); // cache the window query since we'll be using it a lot

// set initial values
var oldWindowWidth = win.width();

// each time we resize
win.on('resize', function() {
  // get the new width
  var newWindowWidth = win.width();

  // compare it to the old width
  if (newWindowWidth > oldWindowWidth) {
    console.log('increased');
  }
  else if (newWindowWidth < oldWindowWidth) {
    console.log('descreased');
  }

  // update the old width
  var oldWindowWidth = newWindowWidth;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>