Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
2.0 kB
0
Indexable
Never
// mega menu js
var menuElement = "#my-mega-menu .menu-item";
var mobileToggle = '.fl-menu-mobile-toggle';

jQuery(document).ready(function() {
  // exit if Beaver Builder is running
  if (jQuery('body').hasClass('fl-builder-edit')) return true;

  // add the helper parent class to the mega menu for mobile
  jQuery('[id^="mega-"]').first().parent().addClass('mega-mobile-container');

  // set top location of mega menu on window resize
  function setMegaMenuTop() {
    var topValue = 0;
    if (isMobile()) {
      topValue = jQuery(mobileToggle).offset().top + jQuery(mobileToggle).outerHeight();
      jQuery('.mega-mobile-container').css('top', topValue + 'px');
    } else {
      jQuery('.mega-mobile-container').css('top', '');
      jQuery('.show-mega-mobile').removeClass('show-mega-mobile');
    }
    jQuery(menuElement).each(function() {
      var menuItem = jQuery(this);
      var megaItem = jQuery("#" + "mega-" + menuItem.text().replace(/\s/g, "-").toLowerCase());
      if (megaItem.length) { // if it's a mega menu item
        // set up hover listeners for menu items
        menuItem.off('mouseenter mouseleave').on('mouseenter mouseleave', function() {
          if (!isMobile()) {
            megaItem.toggleClass('show-mega');
          }
        });

        // the rest should be handled with CSS
        if (isMobile()) {
          megaItem.css('top', topValue + 'px');
          topValue += megaItem.height();
        } else {
          topValue = menuItem.offset().top + menuItem.outerHeight();
          megaItem.css('top', topValue + 'px');
        }
      }
    });
  }

  // call setMegaMenuTop on window resize
  jQuery(window).on('resize', setMegaMenuTop).resize();

  // toggle mega menu on mobile
  jQuery(mobileToggle).on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    jQuery('body').toggleClass('show-mega-mobile');
  });
});

function isMobile() {
  return jQuery(mobileToggle).is(':visible');
}