I have been using the following mobile menu code for some time now and it has been working well. I have implemented a CSS animation so that when the menu button is clicked, it smoothly scrolls into view. However, I have noticed that the animation does not work on the very first click, but it works fine on subsequent clicks. If you notice any issues in my jQuery code, please feel free to point them out as I am still learning jQuery.
Any help or insights on what I might be overlooking to resolve this issue would be greatly appreciated.
jQuery(function() {
// Display the menu when the button is clicked
jQuery('#menu_btn').click(function() {
if(jQuery('#menu').is(':visible')) {
jQuery('#menu').animate({ left: '-100%' }, 'slow', function () {
jQuery("#menu").css('display', 'none');
jQuery('#menu_close').css('display', 'none');
});
} else {
jQuery("#menu").css('display', 'block');
jQuery('#menu').animate({ left: '0' }, 'slow', function(){
jQuery('#menu_close').css('display', 'block');
});
}
});
// Close the menu when the X button is clicked
jQuery('#menu_close').click(function() {
jQuery('#menu').animate({ left: '-100%' }, 'slow', function () {
jQuery("#menu").css('display', 'none');
});
});
callOnResize();
});
jQuery(window).resize( function(){
callOnResize();
});
function callOnResize() {
var winwidth = jQuery(window).width();
if (winwidth < 760) {
jQuery( '#menu' ).css({ display: 'none' });
jQuery('#menu').animate({ left: '0' }, 'slow');
} else if (winwidth >= 760) {
jQuery( '#menu' ).css({ display: 'block' });
}
}
The HTML structure of the menu is very simple, using an unordered list (ul) output by WordPress:
<div id="menu">
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
</div>