I'm working with Craft CMS and using javascript to load pages via AJAX. I use a global javascript variable to determine if my navigation menus is open or closed. Simple menuOpen = false
or menuOpen = true
. And then to open or close the menu:
$(".header a.nav").on("touchstart click", function(e){
e.stopPropagation();
e.preventDefault();
if ( menuOpen == true ){
closeMenu();
} else if ( menuOpen == false ) {
openMenu();
}
});
openMenu = function() {
$("body").addClass("menu-open");
$("nav.menu").removeClass("is-closed").addClass("is-open");
$("header a.nav").addClass("x").removeClass("menu");
menuOpen = true;
}
closeMenu = function() {
$("body").removeClass("menu-open");
$("header a.nav").addClass("menu").removeClass("x");
$("nav.menu").removeClass("is-open").addClass("is-closed");
menuOpen = false;
setTimeout(function(){
$("nav.menu").removeClass("is-closed");
}, 150);
}
When I change pages via AJAX I have to close the menu, so in my AJAX success function, I run closeMenu()
to ensure it's closed when the new page is revealed.
$.ajax({
type: 'POST',
url: href,
data: {},
success: function(result){
// Add in new content
$main.html(result);
// close menu
closeMenu();
// lots of other stuff omitted here to show you the relevant part
}
});
My problem is that after an AJAX page load, when I go to open the menu again it appears as if the global variable menuOpen
is not being read correctly, or the if statement is failing somehow.
The result is that the menuOpen
and menuClose
functions appear to both run at the same time, even though the if statement only allows one or the other to run. This means the menu can never open after any AJAX page load because it closes simultaneously to opening.
Is there something wrong with the way I'm using/changing variables, or something wrong with my if statement?