0

I have a menu in which I am trying to get the sub menu to appear on click as opposed to hover. I have the hover styles set and working so when I hover the sub-nav appears as a block element. Not having any luck removing the hover and trying to add click event. If the parent link is clicked the page just refreshes.

const subMenuLink = document.querySelector(".main-nav .menu .menu-item-has-children");
const subMenu = document.querySelector(".main-nav .menu .menu-item-has-children ul");

subMenuLink.addEventListener("click", toggleMenu);

function toggleMenu() {
  if (subMenu.classList.contains("visible")) {
    subMenu.classList.remove("visible");
  } else {
    subMenu.classList.add("visible");
  }
}

I feel like this is on track...but not so yet! Any suggestions please, thank you

1
  • 1
    We need to see the CSS and the HTML before we can help you fix your error.
    – Pixelsmith
    Commented Sep 27, 2021 at 23:54

1 Answer 1

0

This will add new classes to your menus triggered by click event. tell the default that you wish to not hover to have css of li:hover {display:none;}

jQuery(document).ready(function($){
    $('.nav-menu .menu-item-has-children').on("click", function(e){
            e.stopPropagation();
            if($(this).is("li")){
                if($(this).hasClass('opened')){
                    $(this).addClass('closed');
                }else{$(this).removeClass('closed');}
                $(this).siblings().children('.sub-menu').removeClass('visible');
                $(this).siblings().removeClass('current-menu-parent opened');
                $(this).toggleClass('current-menu-parent opened');
                $(this).children('.sub-menu').toggleClass('visible');
            }
            else{
                if($(this).parent().hasClass('opened')){
                    $(this).parent().addClass('closed');
                }else{$(this).parent().removeClass('closed');}
                $(this).parent().siblings().children('.sub-menu').removeClass('visible');
                $(this).parent().siblings().removeClass('current-menu-parent');
                $(this).parent().children('.sub-menu').toggleClass('visible');
                $(this).parent().toggleClass('current-menu-parent opened');
            }
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.