Zeev Katz Zeev Katz - 10 months ago 47
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();



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

if (resizeWidth > width) {

width = width + 1;

} else {

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 Source

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) {
  else if (newWindowWidth < oldWindowWidth) {

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