Skip to content
Advertisement

How to handle event element in container?

I want to click btnToggle, Navigation will run but I don’t know why this code sometimes is successful, sometimes is unsuccessful.

Help me please, thanks all

const nav = document.querySelector(".header-nav");
const btnToggle = document.querySelector(".header__btn-toggle");
document.addEventListener("click", (e) => {
  if (e.target.className == "header__btn-toggle") {
    nav.style.right = "0";
    // right to left
  } else {
    nav.style.right = "-100%";
    //left to right
  }
})
<header class="header">
  <a href="#" class="header__logo">
    <img src="./assets/logo.png" alt="Tvelia">
  </a>
  <ul class="header-nav">
    <a href="#" class="header-nav__item header-nav__item--active">Home</a>
    <a href="#" class="header-nav__item">Adventures</a>
    <a href="#" class="header-nav__item">About</a>
    <a href="#" class="header-nav__item">Contact</a>
    <a href="#" class="header-nav__item">Login</a>
    <a href="#" class="header-nav__item">Signup</a>
  </ul>
  <div class="header__btn-toggle">
    <div></div>
    <div></div>
    <div></div>
  </div>
</header>

Advertisement

Answer

You’re pretty close. Because you attached the event listener to document, your callback function will actually run if you click anywhere on the page. And because browsers have something called event bubbling, that might be the cause of your inconsistencies.

Instead, you should put the event listener on the button only. I would do it like this:

const nav = document.querySelector(".header-nav");
const btnToggle = document.querySelector(".header__btn-toggle");
btnToggle.addEventListener("click", () => { nav.style.right = "0" })
const moveNavRight = (e) => {
    if (e.target !== btnToggle) nav.style.right = "-100%"
}
// If you wanted to change the hide effect to only work when you click the nav 
// (not anywhere on the page), you would change the following line to
// nav.addEventListener("click", moveNavRight)
document.addEventListener("click", moveNavRight)

Here, I extracted the moveNavRight out to a separate function for a bit more clarity. So how this code would work is: if you click on btnToggle, the nav will move to right 0. But if you click on the page/document anywhere else, then the nav will move to right -100%.

Hope this is what you were looking for!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement