Reputation: 1508
I'm using the following code if for a responsive mobile menu. The problem is with the resize event. On scrolling the menu on a mobile touch screen the menu disappears.
if (document.getElementById("burger-check")) {
var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
if (viewportWidth > 768) {
document.getElementById("burger-check").checked = true;
} else {
document.getElementById("burger-check").checked = false;
}
window.addEventListener('resize', function () {
viewportWidth = window.innerWidth || document.documentElement.clientWidth;
if (viewportWidth > 768) {
document.getElementById("burger-check").checked = true;
} else {
document.getElementById("burger-check").checked = false;
}
}, {
passive: false
});
}
Upvotes: 0
Views: 57
Reputation: 34
function myFunction(x) {
if (x.matches) { // If media query matches
document.body.style.backgroundColor = "yellow";
} else {
document.body.style.backgroundColor = "pink";
}
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addEventListener("change", myFunction) // Attach listener function on state changes
you can also use matchMedia then get the max-width https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_matchmedia
Upvotes: 1