Currently, I am encountering a small dilemma with a .on
function and AJAX in conjunction with a mobile menu. The mobile menu is located in the header of a site that relies heavily on AJAX for its content loading. This poses an issue because when an AJAX call is made, the header and footer are not reloaded, causing the 'state' of the menu toggle to be lost.
When I initially click on the hamburger icon to open the menu and then subsequently click on it again to close it, everything works smoothly. However, as soon as I navigate to another page by clicking on a link, the state of the menu gets disrupted, resulting in some unexpected behavior where the menu opens and closes in just one click, among other odd outcomes.
Previously, I was using the slideToggle()
method, but later decided to use a class instead. My idea was to dynamically remove and add this class to handle the opening and closing of the menu, and then reset the class during the AJAX callback once the new page has successfully loaded...
$('.menu-trigger').on('click touchstart', function(e) {
var $this = $(this);
if ($this.is('.non-active')) {
$('.menu-trigger').addClass('active').removeClass('non-active');
$('.menu').addClass('open');
} else {
$('.menu-trigger').removeClass('active').addClass('non-active');
$('.menu').removeClass('open');
}
});
$(document).on('pjax:end', function() {
$('.menu-trigger').removeClass('active').addClass('non-active');
$('.menu').removeClass('open');
});
Has anyone encountered a similar issue before? If so, how did you work around it?