dimanche 25 février 2018

Remove class from nav when sibling is clicked

I've created a navigation that highlights whatever menu item is selected by adding an 'active' class. If you click the body it removes the active class from the menu item and starts over. It works as expected except when you click a sibling on the menu. The active class is added to the newly clicked menu item, but it also remains on the old one. I wrote code that is suppose to loop through all menu items to see if any of them have the 'active' class, remove the class and then add the 'active' class to the new selection. It's not working.

What am I doing wrong? Also is there any easier way to do this? I need to solve this with vanilla Javascript. I can't use jQuery.

// html

<ul class="nav-items">
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
   <li class="nav-item"></li>
</ul>

// js

if (navItems) {
    navItems.addEventListener("click", function(e) {
        var background = document.querySelector('.background');
        var callout = document.querySelectorAll('.background, .nav-close')
        console.log(e.target.closest('.nav-item'));

        if (background.style.display !== "block") {
            background.style.display = "block";
            for( let i = 0; i < e.target.closest('.nav-items').children.length; i++ ) {
                console.log(e.target.closest('.nav-items'));
                e.target.closest('.nav-item').classList.remove('active');
            }

            e.target.closest('.nav-item').classList.add('active');

            if (background.style.display === "block") {
                callout.forEach(function(elem) {
                    elem.addEventListener("click", function(event) {
                        background.style.display = "none";
                        console.log('target', e.target);
                        e.target.closest('.nav-item').classList.remove('active');
                    }); 
                });
            }

        } else {
            background.style.display = "none";
            e.target.closest('.nav-item').classList.remove('active');

        }
    })
}

Aucun commentaire:

Enregistrer un commentaire