Search code examples
jqueryif-statementresponsive-designenquire.js

jQuery If/Else statement, to check if element has class produces both results?


I am using the enquire.js library to add JavaScript media queries into a site I am developing.

The issue happens when I initially load the website.

  1. I resize into the 860px breakpoint, and toggle the nav. All works fine and as expected.
  2. Then I resize past 860px.
  3. And once again I resize back into the 860px enquire.js media query. The toggle nav outputs both console messages.

Any ideas?

   enquire.register("screen and (max-width:860px)", {

        match : function()
        {   
            nav_wrapper.removeClass('show').addClass('hide');

            nav_toggle.click(function()
            {
                if((nav_wrapper).hasClass('hide'))
                {
                    console.log('It\'s hidden');
                    nav_wrapper.removeClass('hide').addClass('show');
                }
                else
                {
                    console.log('It\'s opened up');
                    nav_wrapper.removeClass('show').addClass('hide');
                }

            });

        },

        unmatch : function()
        {
            nav_wrapper.removeClass('hide').addClass('show');
        },

    });

Solution

  • Each time you call match, you're adding a new click handler (by doing nav_toggle.click(function(){ ... }) again). They stack up, and they'll each get called. So after the first call to match you have one and probably get the behavior you expect. After the second call to match, you have two, and start getting the wrong behavior. After the third call to match you'd have three...

    Looking at your click handler, there's no reason to do that, just hook it up once (presumably outside of match).

    So for example:

    // Hook up click **once**
    nav_toggle.click(function() {
        if (nav_wrapper.hasClass('hide')) {
            console.log('It\'s hidden bud');
            nav_wrapper.removeClass('hide').addClass('show');
        } else {
            console.log('It\'s opedn up mate');
            nav_wrapper.removeClass('show').addClass('hide');
        }
    
    });
    
    // Respond to screen width changes
    enquire.register("screen and (max-width:860px)", {
    
        match: function() {
            nav_wrapper.removeClass('show').addClass('hide');
        },
    
        unmatch: function() {
            nav_wrapper.removeClass('hide').addClass('show');
        },
    
    });
    

    Side note: I removed the unnecessary () around nav_wrapper in if((nav_wrapper).hasClass('hide')).