E
E
EvgenyBalalaev2017-07-31 12:59:40
JavaScript
EvgenyBalalaev, 2017-07-31 12:59:40

How to remove and add a class in JS (jQuery) on screen resize? Problem after page refresh?

Hello.
Not strong in JS and jQuery, I did everything according to the manual and thanks to tips from articles from the Internet.

There is this HTML:

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      CONTENT
    </div>
  </div>
</div>


Task:
When the screen width is less than 480px, remove the "col-xs-12" class and add the "col-xs-6" class.
Accordingly, if the screen width is MORE than 480px, then the opposite is true.

I write this JS:
$(document).ready(function() {

  $(window).resize(function(){
    var windowWidth = $('body').innerWidth();
    if(windowWidth < 480){$(".number-bullets").removeClass('col-xs-12').addClass('col-xs-4');}
    else{$(".number-bullets").removeClass('col-xs-4').addClass('col-xs-12');}
  });
});


Everything seems to be working, but there is a problem - when the page is updated, all JS flies, that is, the class that was originally put is put back, and if you update the page at a resolution of less than 480px, then when the width is increased, JS works, but in the other direction.

There is, it seems, some kind of check for the width of the screen at the moment, it doesn’t matter if the person narrowed or expanded the screen, refreshed the page or not, everything should always be saved. And after I refresh the page, everything flies.

Help me please.
Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Morgunov, 2017-07-31
@EvgenyBalalaev

You can do it like this:

$(document).ready(function() {
  function checkWidth() {
    var windowWidth = $('body').innerWidth(),
        elem = $(".number-bullets"); // лучше сохранять объект в переменную, многократно чтобы не насиловать 
                                    // страницу для поиска нужного элемента
    if(windowWidth < 480){
      elem.removeClass('col-xs-12');
      elem.addClass('col-xs-4');
    }
    else{
      elem.removeClass('col-xs-4');
      elem.addClass('col-xs-12');
    }
  }

  checkWidth(); // проверит при загрузке страницы

  $(window).resize(function(){
    checkWidth(); // проверит при изменении размера окна клиента
  });
});

V
Vlad, 2017-07-31
@DaFive

Do on page load
$(window).trigger('resize');

F
Froggyweb, 2017-07-31
@Froggyweb

And no one is embarrassed by what css should do js does and through ... Or is it just a bootstrap of everything. If such a site came to me, I would definitely send it for re-layout. Perhaps the layout designers would add the necessary breakpoint or remove the bootstrap

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question