user7121582 user7121582 - 1 month ago 7
jQuery Question

Updating variable on the fly from another variable

I am trying to check conditions depending on variable. Long story short :

a. body_size variable updates on the fly as user resizes window. //got this sorted in other post.

b.Then knowing variable body_size I need to update another variable:

If body_size is less/greater/etc than X (value set by me) then SlidesInView should update itself.

Default SlidesInView is 3.

Everything should happen on the fly. Please see snippet below :



$(document).ready(function() {

var body_size; // this updates correctly

var resizeTimer;

function setContainerWidth() {
body_size = $('.container').width();
}

$(window).resize(function() {

clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {

setContainerWidth();


}, 200);

});
setContainerWidth();
console.log(body_size);

var SlidesInView = 3; // this should update depending on result below :
$(window).on('resize', function() {
setContainerWidth(); // to check width on resize?
if (body_size => 980) {
SlidesInView = 4; // change SlidesInView above if condition is met.
} else if (body_size <= 640) {
SlidesInView = 1; //change SlidesInView above if condition is met.
}
});

console.log(SlidesInView);
}); // doc ready

.container{
height:100vh;
width:100vw;
background:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="container">
</div>




Answer

Don't create a second resize event handler. Instead update slidesInView in the function you already have executed on each resize: setContainerWidth:

$(document).ready(function() {
  var body_size, resizeTimer, slidesInView;

  function setContainerWidth() {
    body_size = $('.container').width();
    slidesInView = body_size >= 980 ? 4 
                 : body_size >= 640 ? 3
                 :                    1;
  }

  $(window).resize(function() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(setContainerWidth, 200);
  });
  setContainerWidth();
});

Some remarks:

  • => is an invalid comparison operator (it has another meaning in the context of arrow functions). Use >= instead;

  • Don't name your variables with a first capital letter. It is common practice to only do that for class/constructor names, not for other variables.

  • The ternary operator (... ? .... : ...) is ideal for how you want to assign a value to slidesInView.

  • When you call just one function in a setTimeout, you can just pass that function as the first argument to setTimeout (make sure to not call it, but pass the function itself), like I did in above code.