Close toggle menu by clicking on an item in the navigation

Asked

Viewed 64 times

0

I have the following codes:

<div class="menu-toggle">
    <div class="one"></div>
    <div class="two"></div>
    <div class="three"></div>
</div>
@media (max-width: 700px) {
    nav {
        padding: 20px 30px 0px;
    }
    nav .navigation {
        display: none;
    }
    .menu-toggle {
        display: grid;
        justify-items: end;
        width: 40px;
        height: 30px;
        margin-top: -5px;
    }
    .one, .two, .three {
        height: 4px;
        width: 80%;
        margin-top: 6px;
        border-radius: 10px;
        background-color: var(--menuToggle);
        transition-duration: 300ms;
    }
    nav.on {
        align-items: unset;
        padding: 26px 0px 0px 0px;
        position: absolute;
        top: 0;
        left: 1px;
        right: 0;
        z-index: 1;
        width: 100vw;
        height: 60vh;
        transition-duration: 200ms;
        box-shadow: var(--boxShadow);
        border-radius: 0px 0px 20px 20px;
        background-color: var(--fullScreen);
    }
let show = true; 

const main = document.querySelector("#main")
const navigation = document.querySelector(".nav")
const menuToggle = navigation.querySelector(".menu-toggle")

menuToggle.addEventListener("click", () => {
    main.style.marginTop = show ? "90px" : "0px";
    
    navigation.classList.toggle("on", show)
    show = !show;
})

It’s a hamburger menu that even works well in the sense of clicking the hamburger to open and clicking the "x" to close. However, when I click on some navigation item (are anchor links) it goes to the specific part of the page, but when I go to the top back, the menu is still open there.

  • Guy would be interesting you edit your question and include the minimum code that to at least simulate your problem, only with these pieces that you put not even the menu is working

  • I would create a function closeMenuToogle(), one can call it through a click event at any page anchor. Every time you click on a navigation link, the function is called.

1 answer

1

The last if checks if the click target was an 'anchor' and if it is not to show, then arrow the style display property as 'None'.

const menu = document.querySelector(".menu-toggle");
let show = true;

menu.addEventListener("click", (event) => {
    event.stopPropagation();
    
    //Oque já faz hoje
    show = !show;
    
    if(event.target.tagName === 'A' && !show)
      menu.style.display = 'none';
})
.two, .one {
  display: 'block';
  height: 32px;
  width: 32px;
}
<div class="menu-toggle">
  <a href='#' class="two">Link1</a>
  <a href='#' class="one">Link2</a>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.