Untitled

mail@pastecode.io avatar
unknown
javascript
a year ago
2.2 kB
1
Indexable
Never
// mega menu js
const menuElement = document.querySelectorAll("#my-mega-menu .menu-item");
const mobileToggle = document.querySelector('.fl-menu-mobile-toggle');

if (document.body.classList.contains('fl-builder-edit')) {
  // Exit if bb is running
  return;
}

// Add the helper parent class to the mega menu for mobile
const megaMobileContainer = document.querySelector('[id^="mega-"]').parentElement;
megaMobileContainer.classList.add('mega-mobile-container');

function handleResize() {
  const isMobile = mobileToggle.offsetParent !== null;

  if (isMobile) {
    // Set top value of container
    const topValue = mobileToggle.offsetTop + mobileToggle.offsetHeight;
    megaMobileContainer.style.top = topValue + 'px';
  } else {
    megaMobileContainer.style.top = '';
    document.querySelectorAll('.show-mega-mobile').forEach(elem => elem.classList.remove('show-mega-mobile'));
  }

  menuElement.forEach(menuItem => {
    const megaItem = document.querySelector("#" + "mega-" + menuItem.textContent.replace(/\s/g , "-").toLowerCase());

    if (megaItem) { // if it's mega anything
      if (!isMobile) {
        // Set up hover listeners for menu items
        menuItem.addEventListener('mouseenter', () => {
          document.querySelector("#" + "mega-" + menuItem.textContent.replace(/\s/g , "-").toLowerCase()).classList.add('show-mega');
        });
        menuItem.addEventListener('mouseleave', () => {
          document.querySelector("#" + "mega-" + menuItem.textContent.replace(/\s/g , "-").toLowerCase()).classList.remove('show-mega');
        });
      }

      if (isMobile) {
        megaItem.style.top = megaMobileContainer.offsetTop + 'px';
        megaMobileContainer.style.top = megaMobileContainer.offsetTop + megaItem.offsetHeight + 'px';
      } else {
        document.body.classList.remove('show-mega-mobile');
        const topValue = menuItem.offsetTop + menuItem.offsetHeight;
        megaItem.style.top = topValue + 'px';
      }
    }
  });
}

window.addEventListener('resize', handleResize);
handleResize();

mobileToggle.addEventListener('click', event => {
  event.preventDefault();
  event.stopPropagation();
  document.body.classList.toggle('show-mega-mobile');
});