Mobile menu disappears on scroll (pure javascript)

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
});

}

26 thoughts on “Mobile menu disappears on scroll (pure javascript)”

Leave a Comment