'Setting display = 'none' in javascript taking precedence over CSS in media query

I have a simple web page in which I have a navigation bar enclosed in nav tags. I use a media query to hide this navigation bar when the viewport is less than 700px wide (by setting display: none for the nav tag in CSS), and to display this navigation bar when the viewport is 700px wide or wider (by setting display: block for the nav tag in CSS). This works exactly how I want when I initially load my page. I can resize the viewport as many times as I want and see my desired effect (disappearing and reappearing of the navigation bar) every time.

I also have some javascript on this page. First, I get a reference to the nav element as follows:

const mynav = document.querySelector('nav');

When the navigation bar is hidden, clicking a button results in the following code running to display the navigation bar:

mynav.style.display = 'block';

After the navigation bar has been displayed using javascript, clicking the same button results in the following code running to hide the navigation bar:

mynav.style.display = 'none';

This javascript is working how I had hoped, except for one problem. After javascript has been used to display and then hide the navigation bar in this manner, the navigation bar remains hidden from that point forward no matter what I do. It seems like setting display = none in javascript takes precedence over my CSS in my media query, so that if I make my viewport larger again, I cannot get the navigation bar to reappear.

If anyone here can tell me if there is a way that I can make the effect of my javascript "temporary" in a way that after it runs, the CSS in my media query would still work?

Any advice or suggestions will be greatly appreciated.

Thanks in advance, Paul



Solution 1:[1]

test with toggle, I think it will solve your problem:

   btnNav.onclick = function affiche(){  
        navAffich.classList.toggle("show");
    }

in css creat a class show :

.show {
        display:block;
    }

Read the documentation about toggle here with w3shools or mdn

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sam10