How to check Body Width every time you change Jquery Size

Asked

Viewed 235 times

-2

I was checking the size of body for $(window).resize but I realize that when starting the page initially the right size but does not apply to classes. Follows the Code:

jQuery.noConflict()(function($) {
  "use strict";

  $(document).ready(function() { // Inicializar app quando o documento esta pronto
    $(window).on('load', function() {
      $('.preloader').delay(350).fadeOut(); // Page Preloading
      $('body').hide().delay(350).show(); // Force Chrome to repaint fonts
      checkSize();
      $(window).resize(checkSize);
    });
  });

  function checkSize() {
    var width = $(window).width();
    if (width >= 320 || width <= 480) {
      $('.teste').addClass('celular').removeClass('desktop phablet').html('Celular: '+width);
    } else if (width >= 481 || width <= 767) {
      $('.teste').addClass('phablet').removeClass('desktop celular').html('Phablet: '+width);
    } else {
      $('.teste').addClass('desktop').removeClass('celular phablet').html('Desktop: '+width);
    }
  }

}(jQuery)); // Passar em (jQuery):
#body {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="body">
  <div class="teste"></div>
</div>

1 answer

3


In the size check you used the OR operator, this way it always ends up entering the first if, after all the page is always larger than 320 or smaller than 480

if (width >= 320 || width <= 480)

The correct thing would be to use the AND operator

if (width >= 320 && width <= 480) {
    //se for maior ou igual que 320 E menor ou igual a 480
} else if (width >= 481 && width <= 767) {
    //se for maior ou igual a 481 E menor ou igual a 767
} else {
    //em qualquer outro caso
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.