Referring to the example code below. CSS is not changing the display value after the js function changes it.
Expected example behaviors:
- narrowing window hides "nav display"
- widening window displays "nav display"
- clicking "toggleNav" toggles visibility of "nav display"
Unexpected example behaviors:
- clicking "toggleNav" disables the effect of window width
/* toggle between showing and hiding nav when the user clicks on toggleNav */
function toggleNav() {
var x = document.getElementById("nav");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
#nav {display: block; } /* display is not restored after js function */
/* narrow window */
@media screen and (max-width: 70rem) {
#nav {display: none } /* display is not removed after js function */
}
<div>
<!-- button to toggle nav display -->
<a href="javascript:void(0);" class="icon" onclick="toggleNav()">
<div>toggleNav</div>
</a><br>
<nav id="nav">
<h1>nav display</h1>
</nav>
</div>
<p>Initially, @media width toggles nav display.</p>
<p>After running toggleNav() function, @media width does nothing.</p>
Apparently, CSS does not change display value after js changes it.
Is there some way for media max-width to change a display value after js changes it?
ANSWER: The solution is to use js for all show and hide:
<!DOCTYPE html>
<!-- based on https://www.w3schools.com/howto/howto_js_media_queries.asp -->
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>dropbtn</title>
<script src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
</head>
<body>
<div>
<!-- button to toggle nav display -->
<a href="javascript:void(0);" class="icon" onclick="toggleNav()">
<div>toggleNav</div>
</a><br>
<nav>
<h1>nav display</h1>
</nav>
</div>
<p>Initially, @media width toggles nav display.</p>
<p>After running toggleNav() function, @media width does nothing.</p>
<script>
/* toggle between showing and hiding nav when the user clicks on toggleNav */
function toggleNav() {
$("nav").toggle();
}
/* if narrow window, hide nav, if wide window show nav */
function wideShowNav(x) {
if (x.matches) {
$("nav").hide();
} else {
$("nav").show();
}
}
var x = window.matchMedia("(max-width: 70rem)")
wideShowNav(x) // Call listener function at run time
x.addListener(wideShowNav) // Attach listener function on state changes
</script>
</body>
</html>