Domanda

I'm trying to not depend of jquery by using native javascript.

The button does not work but the if statement which wants to express: if there is the class mobile-menu-open and somebody clicks or tabs on any part of the site I will see eureca on my console.

The intention is that if the user clicks anywhere else this class mobile-menu-open is removed.

(function(){
  "use strict";

    var mobileButton = document.querySelectorAll('[data-js="mobile-menu"]')[0];

    mobileButton.addEventListener('click', function(){

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

        if( mobileButton.classList.contains('mobile-menu-open') && document.body.addEventListener('click') ){
            console.log('eureca');
        }

    });


})();

Somebody could help me with this?

È stato utile?

Soluzione

Since you just want to support IE9+ this should do the trick:

function toggleClass(elem,cls) {
    var classes = elem.className.split(/\s+/);
    var search = classes.indexOf(cls);

    if(search >= 0) {
        classes.splice(search,1);
    } else {
        classes.push(cls);
    }

    elem.className = classes.join(' ');
}

function menuOpen() {
    var cls = 'mobile-menu-open';
    toggleClass(document.body,cls);

    if(document.body.className.split(/\s+/).indexOf(cls) >= 0) {
        console.log('menu open'); }
    }

function init() {
    var mobileButtons = document.querySelectorAll('[data-js="mobile-menu"]');

    if(mobileButtons.length>0) {
        mobileButtons[0].addEventListener('click',menuOpen,false);
    }
}

document.addEventListener('DOMContentLoaded',init,false);

The other events I had you look at were in case you wanted to develop something that also supports antiquated versions of IE.

Note: If you value performance, querySelectorAll is not particularly fast so you may have better results doing getElementsByTagName('*') first (or a more specific tag name if possible) then looping through the resultant nodeList.

Edit: Instead of using classList I'm just using the className attribute and splitting it by whitespace to get an array of classes. It searches for the given class name in that array. If it finds it, it removes it by the index, and if it doesn't, it adds it. It then sets className to the array joined with spaces.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top