A single-page or one-page website needs its mobile nav menu tray to automatically collapse on click. However, it doesn’t always happen by default in most cases.
For example, if you build a one-page website using WordPress and Elementor Pro, Elegant themes, or Elements Kits, chances are good that you would run into the shown problem below;
[Click on video to play]
As you can see in the video above, the menu tray does not collapse after clicking on a menu item. This problem is not limited to WordPress headers alone. It can also occur if you use a Bootstrap template.
In this post, I will share with you a wonderful jQuery snippet that would help auto collapse the menu tray by mimicking a click event on the [X] icon when a menu item is clicked.
See the final result below;
[Click on video to play]
Subscribe for updates
So, Here is the jQuery Snippet to automatically collapse the nav menu tray on menu click;
For WordPress
Install and activate any plugin that will enable you to add custom JS codes to your website. I recommend Simple Custom CSS and JS plugin.
Copy and paste the following code into your custom JS field.
jQuery(document).ready(function( $ ){ (function($){ $(window).on("load",function(){ $("body").on("click",".menu-item",function(){$(".menu-close")[0].click();}); }); })(jQuery); });
Variables to take care of;
There are just two variables you need to change;
.menu-item = Change it to the CSS class name of your menu items
.menu-close = Change it to the CSS class name of your mobile menu’s close icon.
For an HTML/Bootstrap Template
<script> jQuery(document).ready(function( $ ){ (function($){ $(window).on("load",function(){ $("body").on("click",".menu-item",function(){$(".menu-close")[0].click();}); }); })(jQuery); }); </script>
Please comment below if it worked for you.
Thank for reading!