Mega menu aanpassing

User
<style>
.mega-overlay-mobile {
  display: none;
  position: fixed;
  top: 0; left: 0;
  width: 100%;
  height: 100%;
  background: rgba(244, 241, 241, 0.95);
  z-index: 9999;
  color: #000;
  overflow-y: auto;
}

.mega-overlay-content {
  padding: 40px;
  max-width: 600px;
  margin: 100px auto;
  text-align: center;
}

#close-mega-menu {
    position: absolute;
    top: 0;
    right: 0;
    background: none;
    border: none;
    font-size: 19px;
    color: #000;
    cursor: pointer;
}
  @media screen and (max-width: 768px) {
    .parent-cat {
    margin-bottom: 20px;
  }
  .parent-cat .subcategories,
  .parent-cat .top-products {
  display: none;
  margin-top: 10px;
}
.parent-cat.active .subcategories,
.parent-cat.active .top-products {
  display: block;
}
.product-item {
  margin-bottom: 10px;
}
  }
  
  
  @media (max-width: 767px) {
	.mega-overlay-mobile {
    display: none;
    position: fixed;
    top: 120px;
    left: 0;
    width: 100%;
    height: 100%;
    background: #fff;
    z-index: 9999;
    color: #000;
    overflow-y: auto;
}
.stuck 	.mega-overlay-mobile { top:69px}
.mega-overlay-content {
    padding: 40px 40px 20px 20px;
    max-width: 600px;
    margin: 0px auto;
    text-align: center;
}

.mega-overlay-mobile .mega-overlay-content {
  
    height: calc(100% - 120px);
}

.stuck .mega-overlay-mobile .mega-overlay-content {

    height: calc(100% - 70px);
}

}
</style>

Search

Assistant
To **adjust your mega menu so that if a category has no subcategories**, the **top 3 products from the parent category** are shown instead (instead of skipping the products section or showing nothing), you need to:

### βœ… Modify this block in **mobile menu**:
Inside this section:

if ($has_subcats) {

You need to **add an `else` block** to handle when there are **no subcategories**, and show products directly from the **parent category**.

### βœ… βœ… Updated Code Snippet (for mobile version):
Locate this part inside your `foreach ($parent_cats as $cat)` loop:

#### πŸ”½ **Replace this section:**

if ($has_subcats) {
  $sub_display = $loopi === 0 ? 'block' : 'none';
  echo "<ul class='subcategories' style='display: {$sub_display};'>";
  ...
  echo "</ul>";
}

#### βœ… With this:

if ($has_subcats) {
  $sub_display = $loopi === 0 ? 'block' : 'none';
  echo "<ul class='subcategories' style='display: {$sub_display};'>";
  $subLoopIndex = 0;

  foreach ($subcategories as $subcat) {
    $sub_link = esc_url(get_term_link($subcat));
    $open_class = $subLoopIndex === 0 && $loopi === 0 ? 'open-subcat' : '';
    echo "<li class='subcat-item {$open_class}'>";
    echo "<a href='{$sub_link}' class='subcat-toggle' data-sub-id='{$subcat->slug}'>{$subcat->name}</a>";

    if($subLoopIndex==0) {
      $style = ($open_class) ? 'display:block;' : 'display:none;';
      echo "<ul class='subcat-products' style='{$style}'>";

      $products = wc_get_products([
        'limit' => 3,
        'status' => 'publish',
        'category' => [$subcat->slug],
      ]);
      $mainCategoryName = $cat->name;
      $template = get_stylesheet_directory() . '/partials/mega-menu-product-tmpl.php';
      if (file_exists($template)) {
        include $template;
      } else {
        echo '<p>Results template missing.</p>';
      }

      echo "</ul>";
    } else {
      echo "<ul class='subcat-products' data-sub-id='{$subcat->slug}' style='display:none;'></ul>";
    }
    echo "</li>";
    $subLoopIndex++;
  }

  echo "</ul>"; // End subcategories list

} else {
  // No subcategories β€” show products from parent category
  echo "<ul class='subcategories' style='display: block;'>";
  echo "<li class='subcat-item open-subcat'>";
  echo "<span class='subcat-toggle' data-sub-id='{$cat->slug}'>{$cat->name}</span>";
  echo "<ul class='subcat-products' style='display:block;'>";

  $products = wc_get_products([
    'limit' => 3,
    'status' => 'publish',
    'category' => [$cat->slug],
  ]);
  $mainCategoryName = $cat->name;
  $template = get_stylesheet_directory() . '/partials/mega-menu-product-tmpl.php';
  if (file_exists($template)) {
    include $template;
  } else {
    echo '<p>Results template missing.</p>';
  }

  echo "</ul></li></ul>";
}

### βœ… Summary:
– This fallback code ensures **products are displayed from the parent category** if no subcategories exist.
– It reuses your existing template (`mega-menu-product-tmpl.php`) to keep consistency.

Let me know if you want the same behavior added to the **desktop version** as well.

User
Assistant
Here's your **adjusted version** of the “ loop. This modification includes product display from the **main category itself** when **no subcategories exist**.

### βœ… Updated Code:

<ul class="product-menu">
  <?php
  $categoriesallow = [1252,9,17,1240,1068,35,37,38,1177,1234,1229,40,785,1176,757,1160,1052];
  $parent_cats = get_terms([
    'taxonomy' => 'product_cat',
    'parent' => 0,
    'hide_empty' => true,
    'orderby' => 'include',
    'include' => $categoriesallow
  ]);

  $firstCatId = 0;
  $firstCatName = '';
  $loopi = 0;

  foreach ($parent_cats as $cat) :
    $term_link = esc_url(get_term_link($cat));
    $subcategories = get_terms([
      'taxonomy' => 'product_cat',
      'parent' => $cat->term_id,
      'hide_empty' => true,
    ]);

    $has_subcats = !empty($subcategories);
    $active = $loopi === 0 ? 'active-cat' : '';

    echo "<li class='parent-cat {$active}'>";
    echo "<div class='category-item' data-cat-id='{$cat->term_id}'>";
    echo "<span class='toggle-subcat dd'></span> ";
    echo "<a href='{$term_link}'>{$cat->name}</a>";
    echo "</div>";

    if ($has_subcats) {
      $sub_display = $loopi === 0 ? 'block' : 'none';
      echo "<ul class='subcategories' style='display: {$sub_display};'>";
      $subLoopIndex = 0;

      foreach ($subcategories as $subcat) {
        $sub_link = esc_url(get_term_link($subcat));
        $open_class = $subLoopIndex === 0 && $loopi === 0 ? 'open-subcat' : '';
        echo "<li class='subcat-item {$open_class}'>";
        echo "<a href='{$sub_link}' class='subcat-toggle' data-sub-id='{$subcat->slug}'>{$subcat->name}</a>";

        if ($subLoopIndex == 0) {
          $style = 'display:block;';
          echo "<ul class='subcat-products' style='{$style}'>";

          $products = wc_get_products([
            'limit' => 3,
            'status' => 'publish',
            'category' => [$subcat->slug],
          ]);
          $mainCategoryName = $cat->name;
          $template = get_stylesheet_directory() . '/partials/mega-menu-product-tmpl.php';
          if (file_exists($template)) {
            include $template;
          } else {
            echo '<p>Results template missing.</p>';
          }

          echo "</ul>";
        } else {
          echo "<ul class='subcat-products' data-sub-id='{$subcat->slug}' style='display:none;'></ul>";
        }

        echo "</li>";
        $subLoopIndex++;
      }

      echo "</ul>"; // End subcategories
    } else {
      // No subcategories, show products from main category
      echo "<ul class='subcategories' style='display:block;'>";
      echo "<li class='subcat-item open-subcat'>";
      echo "<span class='subcat-toggle' data-sub-id='{$cat->slug}'>{$cat->name}</span>";
      echo "<ul class='subcat-products' style='display:block;'>";

      $products = wc_get_products([
        'limit' => 3,
        'status' => 'publish',
        'category' => [$cat->slug],
      ]);
      $mainCategoryName = $cat->name;
      $template = get_stylesheet_directory() . '/partials/mega-menu-product-tmpl.php';
      if (file_exists($template)) {
        include $template;
      } else {
        echo '<p>Results template missing.</p>';
      }

      echo "</ul></li></ul>";
    }

    echo "</li>"; // End parent category
    $loopi++;
  endforeach;
  ?>
</ul>

### βœ… What’s Improved:
– Handles both cases:
– βœ… If **subcategories exist** β†’ shows their products.
– βœ… If **no subcategories** β†’ directly shows products from the **parent category**.

Let me know if you want to **load more than 3 products**, enable **AJAX switching**, or need this for the **desktop version too**.

User
const megaMenu = $('#mega-menu');
const triggerItem = $('.shop-megamenu');
const arrow = $('.shop-megamenu .mega-arrow');

// Show/hide mega menu on hover
triggerItem.hover(
function () {
//alert('hover');
megaMenu.stop(true, true).slideDown(600);
},
function () {
setTimeout(() => {
if (!megaMenu.is(':hover')) {
megaMenu.stop(true, true).slideUp(600);
}
}, 200);
}
);
make above on click also and prevene efaulr

Assistant
To make your **mega menu toggle on click instead of hover**, and also **prevent default behavior** (like navigation), here's how you can **adjust your jQuery code**:

### βœ… Updated Script for Click Toggle:

jQuery(document).ready(function ($) {
  const megaMenu = $('#mega-menu');
  const triggerItem = $('.shop-megamenu');
  const arrow = $('.shop-megamenu .mega-arrow');

  let isMegaOpen = false;

  // Handle click toggle
  triggerItem.on('click', function (e) {
    e.preventDefault(); // Prevent default anchor click (if any)
    e.stopPropagation(); // Stop event bubbling

    if (isMegaOpen) {
      megaMenu.stop(true, true).slideUp(400);
    } else {
      megaMenu.stop(true, true).slideDown(400);
    }

    isMegaOpen = !isMegaOpen;
  });

  // Close the mega menu if click occurs outside
  $(document).on('click', function (e) {
    if (!$(e.target).closest('#mega-menu, .shop-megamenu').length && isMegaOpen) {
      megaMenu.stop(true, true).slideUp(400);
      isMegaOpen = false;
    }
  });
});

### βœ… Key Features:
– βœ… Opens and closes on `.shop-megamenu` click.
– βœ… Prevents default behavior (`e.preventDefault()`).
– βœ… Click outside will close the menu (`document` click).
– βœ… Smooth animation with `slideDown` / `slideUp`.

Let me know if you also want **mobile toggle behavior** with the same logic.

User
no I also want on click , hover needs to persist
Assistant
Got it β€” you want:

βœ… **Hover** to still open and close the mega menu
βž• **Click** to also open/close the mega menu (with toggle)
βœ… **Prevent default behavior** on click
βž• **Click outside** should close the menu

Here’s the **final combined jQuery solution**:

### βœ… Final Script: Hover + Click Toggle

jQuery(document).ready(function ($) {
  const megaMenu = $('#mega-menu');
  const triggerItem = $('.shop-megamenu');
  const arrow = $('.shop-megamenu .mega-arrow');

  let isMegaOpen = false;
  let closeTimeout;

  // Hover behavior
  triggerItem.hover(
    function () {
      clearTimeout(closeTimeout);
      megaMenu.stop(true, true).slideDown(300);
      isMegaOpen = true;
    },
    function () {
      closeTimeout = setTimeout(() => {
        if (!megaMenu.is(':hover')) {
          megaMenu.stop(true, true).slideUp(300);
          isMegaOpen = false;
        }
      }, 200);
    }
  );

  megaMenu.hover(
    function () {
      clearTimeout(closeTimeout);
    },
    function () {
      closeTimeout = setTimeout(() => {
        megaMenu.stop(true, true).slideUp(300);
        isMegaOpen = false;
      }, 200);
    }
  );

  // Click toggle
  triggerItem.on('click', function (e) {
    e.preventDefault();
    e.stopPropagation();

    if (isMegaOpen) {
      megaMenu.stop(true, true).slideUp(300);
      isMegaOpen = false;
    } else {
      megaMenu.stop(true, true).slideDown(300);
      isMegaOpen = true;
    }
  });

  // Click outside to close
  $(document).on('click', function (e) {
    if (!$(e.target).closest('#mega-menu, .shop-megamenu').length && isMegaOpen) {
      megaMenu.stop(true, true).slideUp(300);
      isMegaOpen = false;
    }
  });
});

### βœ… This Covers:
– βœ… Hover in/out behavior with delay and persistence
– βœ… Click toggle (preventing default)
– βœ… Close on outside click

Let me know if your `.shop-megamenu` is an “ tag or a “, so we can adjust `e.preventDefault()` use if needed.

Leave a Comment

Your email address will not be published. Required fields are marked *