user2969934
user2969934

Reputation: 79

jQuery run script the moment screen size gets below X pixels

Is it possible to run a script when the screen size gets above or below a certain point, but only at that certain point? I have a function that takes two paramters, and i would like those two parameters to change if the screen size is below 769 pixels. So i have used the classic:

$( window ).resize(function() {
  if ($(window).width() < 769) {
     foobar(foo1, bar1);
  }
  else {
     foobar(foo2, bar2);
  } 
});

that works, but that runs foobar every time the window is resized. The problem is that i do not want the function to be executed if you resize the browser from e.g 500 to 600 px because that means it executes if you go from portrait to landscape on a smartphone, i only want it to be executed the moment it goes below or above 768 px. Any ideas?

Upvotes: 0

Views: 783

Answers (2)

Der Vampyr
Der Vampyr

Reputation: 951

You could change your JS like this:

$( window ).resize(function() {
  if ($(window).width() < 769 && !$('html').hasClass('smallWindow')) {
    $('html').addClass('smallWindow');
    foobar(foo1, bar1);
  }
  else if($(window).width() > 769 && $('html').hasClass('smallWindow')) {
    $('html').removeClass('smallWindow');
    foobar(foo2, bar2);
  } 
});

And this brings the advantage, that you can add some stylings for the smaller window etc based on the htmlclass

Upvotes: 1

Rhumborl
Rhumborl

Reputation: 16609

You can keep track of the previous width in a global variable then check when the new and previous widths are either side of 768, so you know you have crossed over the boundary:

var prevWidth = null;

$(function(){
    prevWidth = $(window).width();
    console.log(prevWidth);
})

$(window).resize(function() {
    var newWidth = $(window).width();
    if(prevWidth <= 768 && newWidth > 768) {
        foobar(foo1, bar1);
    }
    else if (prevWidth > 768 && newWidth <= 768) {
        foobar(foo2, bar2);
    }

    prevWidth = newWidth;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Fiddle

Upvotes: 3

Related Questions