How to add and remove class according to viewport

Asked

Viewed 42 times

1

I would like to add a class when the viewport is less than 899px and remove when the viewport is greater than that.

At first my code worked, but without removing the class when the viewport increases.

$(window).resize(function () {
    var viewportWidth = $(window).width();
    if (viewportWidth < 800) {
            document.querySelector('.layout-fixed-header').classList.add("layout-small-menu");
    }
});

What would be the best way to assemble this code?

1 answer

3


Whenever you can cache the elements you search with document.querySelector, especially within a .resize() this may weigh the browser.

My suggestion would be to do this with CSS only... using media queries:

@media screen and (min-width: 801px) {
  .layout-small-menu {
    background-color: blue;
  }
}

@media screen and (max-width: 800px) {
  .layout-small-menu {
    background-color: olive;
  }
}

But to answer your question:

var fixedHeader = document.querySelector('.layout-fixed-header');
$(window).resize(function() {
  var viewportWidth = $(window).width();
  fixedHeader.classList.toggle("layout-small-menu", viewportWidth < 800);
});

In this case I used the .toggle() which adds or removes the class depending on the value of the second argument passed to it.

Browser other questions tagged

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