Adding support for ESCAPE key or click outside to close menu

Created on 4 October 2019, over 5 years ago
Updated 28 February 2024, about 1 year ago

I needed to enable feature to close menu by clicking escape on keyboard or to click outside, so I added this code to cheeseburger_menu.js file:

    function includeCode() {

      var $active = $('.cheeseburger-menu__menu-list-item-link.active');
      var hasActive = $active.length > 0;
      $('.cheeseburger-menu__trigger').on('click touchstart', function (e) {
        $('body, .cheeseburger-menu__wrapper').toggleClass('menu-is-visible');
        $('.cheeseburger-menu__trigger').toggleClass('is-open');
        e.preventDefault();
      });

      // ESC key feateure START
      $(document).keyup(function(e) {
        if (e.keyCode == 27) { // escape key maps to keycode `27`
          if ($(".cheeseburger-menu__trigger").hasClass("is-open")) {
            $('body, .cheeseburger-menu__wrapper').toggleClass('menu-is-visible');
            $('.cheeseburger-menu__trigger').toggleClass('is-open');
          }
        }
      });
      // ESC key feateure END

    //CLICK OUTSIDE OF MENU TO CLOSE IT - START
    $(document).mouseup(function(e)
    {
      var menu_wrapper = $(".cheeseburger-menu__wrapper");
      var trigger = $(".cheeseburger-menu__trigger");

      // if the target of the click isn't the container nor a descendant of the container
      if (!menu_wrapper.is(e.target) && menu_wrapper.has(e.target).length === 0 && trigger.hasClass("is-open") && !trigger.is(e.target))
      {
        // container.hide();
        $('body, .cheeseburger-menu__wrapper').toggleClass('menu-is-visible');
        $('.cheeseburger-menu__trigger').toggleClass('is-open');
      }
    });
    //CLICK OUTSIDE OF MENU TO CLOSE IT - END   

      var scrollTo = function (element, to, duration) {

        var start = element.scrollTop,
            change = to,
            currentTime = 0,
            increment = 20;
            .
            .
            .
            ...rest of the code

I don't have time to make a patch.

Feature request
Status

Fixed

Version

5.0

Component

Code

Created by

🇷🇸Serbia miksha

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024