user4591043
user4591043

Reputation:

resize and calling function

I have this function that when you click on the html it checks the width of a number of elements and compares it with the windows width. I can't get it to work with the resize function. I think I'm calling it wrong.

$(document).ready(function() {

  $(window).resize(function() {
    var conditionWidth = checkWidth()
  });

  function checkWidth() {
    var elementWidth = 1;
    $("div>div").each(function() {
      if ($(this).width() > $("html").width() / 2) {
        elementWidth = 2;
      }
    });
    return elementWidth;
  }

  var conditionWidth = checkWidth()

  $("body").off("click").click(function() {
    alert(conditionWidth);
  });
})
div div {
  position: relative;
  height: 100px;
  width: 100px;
  margin-top: 20px;
}
.rectangle1 {
  background-color: black;
  width: 100px;
}
.rectangle2 {
  background-color: red;
  width: 200px;
}
.rectangle3 {
  background-color: black;
  width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div>
  <div class="rectangle1"></div>
  <div class="rectangle2"></div>
  <div class="rectangle3"></div>
</div>

Upvotes: 0

Views: 71

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

Since you are using var to declare the variable in the resize handler the the variable is local to the resize handler method and the value of the closure scope(dom ready handler) is not updated.

$(document).ready(function () {

    var conditionWidth = checkWidth()

    $(window).resize(function () {
        //when you use var it becomes a local variable
        conditionWidth = checkWidth()
    });

    function checkWidth() {
        var elementWidth = 1;
        $("div>div").each(function () {
            if ($(this).width() > $("html").width() / 2) {
                elementWidth = 2;
            }
        });
        return elementWidth;
    }

    $("body").off("click").click(function () {
        alert(conditionWidth);
    });
})

Upvotes: 1

Related Questions