1. Home
  2. Help Center
  3. Customization
  4. Close mobile menu with anchor links

By default the mobile menu doesn’t automatically close when you click on a link. That’s because it usually loads another page.

However, if you are using anchor links on the main/mobile menu you can use this function to automatically close the off canvas menu.

add_action('wp_footer','autoclose_mobile_menu');
function autoclose_mobile_menu() { ?>
<script>
 jQuery(document).ready(function($) {
  anchorLinks();
  function anchorLinks() {
   $('body').on('click','.mobile-menu a[href*=\\#]', function(e) {
    e.preventDefault;
    if ($(this).hasClass('sliding-menu-nav')) return;
    var target = $(this).attr('href');
    if(target.indexOf(window.location.href) > -1) { 
     target = '#' + target.split('#')[1]
    }
    $(this).closest('.side-menu').find('.et-close').trigger('click');
    $('html,body').animate({scrollTop: $(target).offset().top - $('#header').outerHeight() },'slow');
   });
  }
 });
</script>
<?php }Code language: JavaScript (javascript)

Add the code to wp-content/themes/goya-child/functions.php and clear all caches – the mobile browser cache included.

Was this article helpful?

Related Articles