Can't figure out why my JavaScript is causing issues with my menu.
I've made a mistake in the JavaScript file, but in general it's working fine. The problem arises when you load the page with a width less than 858px, then click on one of the menu items, and later increase the width - the menu disappears. I want to prevent this from happening.
Here is the JavaScript, HTML, and CSS:
const mediaQuery = window.matchMedia("(max-width: 858px)");
// Check if the media query is true
if (mediaQuery.matches) {
// function that hides the menu when a "ul li a" is clicked, and displays it again when clicked repeatly
function hide() {
document.getElementById("hidden").style.display = "none";
// simulate a click event for the class "checkbtn"
document.getElementsByClassName("checkbtn")[0].click();
}
// function that shows the menu when you click the hamburguer icon (fas fa-bars)
function show() {
document.getElementById("hidden").style.display = "inherit";
}
} else {
function hide() {
document.getElementById("hidden").style.display = "inherit";
document.getElementsByClassName("checkbtn")[0].click();
}
function show() {
document.getElementById("hidden").style.display = "inherit";
}
}
// Initial check
handleTabletChange(mediaQuery);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>test</title>
<!-- External Fonts -->
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Ubuntu&display=swap"
rel="stylesheet"
/>
<script src="./main.js"></script>
<!-- Material Design Icons -->
<link
href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet"
/>
<!-- Hamburger Menu Icon -->
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<style>
/* Styling for the menu */
Insert your style here...
</style>
</head>
<body id="body">
<!-- Navigation Menu -->
<nav>
<input type="checkbox" id="check" />
<label for="check" class="checkbtn"
><i class="fas fa-bars" onclick="show()"></i
></label>
<label class="logo"><a href="#body">Name</a></label>
<ul id="hidden">
Items for the navigation menu...
</ul>
</nav>
</body>
</html>