1

So normally i'm used to jQuery and i'm trying to venture into vanilla Javascript. I'm trying to toggle a subnav open and close by clicking on a link, but it only triggers the last item. I'm assuming it is something to do with the loop. Can anyone give me some advice?

    var hasClass = function (elem, className) {
        return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
    }

    var addClass = function (elem, className) {
        if (!hasClass(elem, className)) {
            elem.className += ' ' + className;
        }
    }

    var removeClass = function (elem, className) {
        var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ') + ' ';
        if (hasClass(elem, className)) {
            while (newClass.indexOf(' ' + className + ' ') >= 0 ) {
                newClass = newClass.replace(' ' + className + ' ', ' ');
            }
            elem.className = newClass.replace(/^\s+|\s+$/g, '');
        }
    }

    var navSections = document.querySelectorAll('.nav-toggle');
    for (var i = 0; i < navSections.length; i++) {

        var navSection = navSections[i];

        navSection.addEventListener('click', function(e) {

                console.log(navSection)

                if ( hasClass(navSection, 'nav-section--is-open') ) {
                    removeClass(navSection, 'nav-section--is-open')
                } else {
                    addClass(navSection, 'nav-section--is-open')
                }

        }, false);
    }
Fox
  • 481
  • 3
  • 14
  • in the event listener, use `this` instead of `navSection` - if you want to know why `navSection` is wrong, search for asynchronous code in loops - for this type of code you can dispense with `closures` – Jaromanda X Sep 04 '16 at 12:17
  • @JaromandaX omg! Of course, what a derp! Thank you! – Fox Sep 04 '16 at 12:19
  • nothing wrong with *derp*, just don't be a *herp derp* ;) – Jaromanda X Sep 04 '16 at 12:22

0 Answers0