user7121582 user7121582 - 1 month ago 10
jQuery Question

Updating variable using function result on window resize Jquery

I would like to update global variable on the fly (window resize).
body_size variable should contain result of the function below it.I do understand that variable sits out of scope,however I have no idea how to pass it out. Please help. 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.0.3/jquery.min.js"></script>
<div class="container">
</div>





Basically top variable body_size should update itself with a value whenever user resizes window.

Answer

Variable body_size is getting assigned only on window resize event and its undefined initially when the console.log is executed.

I have modified it to assign on the load.

$(document).ready(function() {

    var body_size; // this should hold the value of function below. This should get updates on window resize.

    var resizeTimer;
  
    function setContainerWidth() {
      body_size = $('.container').width(); 
    }
  
    $(window).resize(function() {

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

        setContainerWidth(); 
        console.log(body_size); //retrieves actual width.

      }, 200);

    });
  
    setContainerWidth();
    console.log(body_size); //retrieves undefined, which means that body_size at the top is not updating.
  }); // doc ready
.container{
  height:100vh;
  width:100vw;
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="container">
</div>