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.
- I resize into the 860px breakpoint, and toggle the nav. All works fine and as expected.
- Then I resize past 860px.
- 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');
},
});
Each time you call
match, you're adding a newclickhandler (by doingnav_toggle.click(function(){ ... })again). They stack up, and they'll each get called. So after the first call tomatchyou have one and probably get the behavior you expect. After the second call tomatch, you have two, and start getting the wrong behavior. After the third call tomatchyou'd have three...Looking at your
clickhandler, there's no reason to do that, just hook it up once (presumably outside ofmatch).So for example:
Side note: I removed the unnecessary
()aroundnav_wrapperinif((nav_wrapper).hasClass('hide')).