R
R
ref21 @ref2019-04-05 16:08:16
css
ref21 @ref, 2019-04-05 16:08:16

Why doesn't the media query work after running the js code?

There is a code after the launch of which the media query does not work.

document.querySelector('.search').onclick = function() {
  var clientWidth = document.body.clientWidth;
  var mnu = document.querySelector('.mnu');
  var sandwichMnu = document.querySelector('.sandwich-mnu');
  var searchBtn = document.querySelector('.search-button');

  if(searchBtn.classList.contains('search-button-active')) {

    searchBtn.classList.remove('search-button-active');
    if(clientWidth > 1620) {
      mnu.style.display = 'flex';
      sandwichMnu.style.display = 'none';
    }

  } else {

    if(clientWidth <= 1850) {
      mnu.style.display = 'none';
      sandwichMnu.style.display = 'flex';
    }

    searchBtn.classList.add('search-button-active');

  }
}

And here is the media query itself:
@media only screen and (max-width: 1620px) 
             .head-navigation .mnu
                    display: none

             .sandwich-mnu
                    display: flex

I can't understand the reason. Maybe it's a matter of priorities?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim Kot, 2019-04-05
@ref21

To avoid problems with specificity (and inline styles have more specificity), it is better to add and remove classes to elements using classList https://developer.mozilla.org/en/docs/Web/API/Elem...
And for classes in styles write the necessary css rules. Take it as a rule and get rid of such problems in the future.

A
Alexander, 2019-04-05
@Krauzer

Javascript and media queries in CSS are not related in any way. They work independently of each other. Why do you think that the reason is in JS?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question