Question

I'm trying to use native javascript, so no jquery is loaded. I want to make an if statement to remove a class in the body element only if it has a class. This way I would avoid it to trigger every time there is a scroll. I basically want it to remove the class only if the window is scrolling and the body has this class applied to it, else it should not trigger.

I tried with this code and it does remove the class, but it's always triggering on scroll, no matter if body has a class or not applied to it. In this case... I see scrollEvent on the console printed with every scroll I do on the page. How do you do this work?

if(document.body.classList){

    window.addEventListener('scroll', function(){
        console.log('scrollEvent');

        document.body.classList.remove('mobile-menu-open');

    });
}
Was it helpful?

Solution 2

You can remove the listener, once your class is removed from the body, that way it won't trigger any more when you scroll.

Here's the code:

var removeMenuClass = function() {
    document.body.classList.remove('mobile-menu-open');
    // remove the scroll listener
    window.removeEventListener('scroll', removeMenuClass, false);
}

// add the scroll listener
window.addEventListener('scroll', removeMenuClass, false);

If needed (let's say when your "mobile-menu" re-opens), you can re-attach the eventListener the same way.

OTHER TIPS

Your if needs to check for that class

window.addEventListener('scroll', function(){
    console.log('scrollEvent');

    // do the following only if it has the class
    if( document.body.classList.contains('mobile-menu-open') ) {

       document.body.classList.remove('mobile-menu-open');

    }

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top