Home > Enterprise >  Hide navbar when li element is been clicked on
Hide navbar when li element is been clicked on

Time:08-04

Hey I'm having trouble hiding the navbar when we click on one of the element like contact or something.. I'm using HTML, JS and CSS..

        <div >
            <img  src="assets/front/img/moon.png" alt="moon dark mode" id="icon">
        </div>
        <a href="#"  id="hamburger">
            <span ></span>
            <span ></span>
            <span ></span>
        </a>
        <nav >
            <ul >
                <li ><a  href="#home">Home</a></li>
                <li ><a  href="#skills">Skills</a></li>
                <li ><a  href="#project">Project</a></li>
                <li ><a  href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>```


    ```const hamburger = document.getElementById('hamburger');
    hamburger.addEventListener('click', function (e) {
        const ul = document.querySelector('nav > ul');
        ul.classList.toggle('menu-slide');
        hamburger.classList.toggle('cross');
    });
    
    function hideDiv() {
        document.getElementsByClassName('ul')[0].style.display = "none";
    }```

CodePudding user response:

Your posted code does not include any part that would react to a click on the li elements. I have added the following:

document.querySelectorAll('li').forEach((li) => li.addEventListener('click', hideDiv));

const hamburger = document.getElementById('hamburger');
    hamburger.addEventListener('click', function (e) {
        const ul = document.querySelector('nav > ul');
        ul.classList.toggle('menu-slide');
        hamburger.classList.toggle('cross');
    });
    
    function hideDiv() {
        document.getElementsByClassName('ul')[0].style.display = "none";
    }
    
  document.querySelectorAll('li').forEach((li) => li.addEventListener('click', hideDiv));
      <header>
      <div >
            <img  src="assets/front/img/moon.png" alt="moon dark mode" id="icon">
        </div>
        <a href="#"  id="hamburger">
            <span ></span>
            <span ></span>
            <span ></span>
        </a>
        <nav >
            <ul >
                <li ><a  href="#home">Home</a></li>
                <li ><a  href="#skills">Skills</a></li>
                <li ><a  href="#project">Project</a></li>
                <li ><a  href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>

CodePudding user response:

You Just Need to call Your function in the HTML Code

 <ul >
            <li ><a  href="#home" onclick="hideDiv()">Home</a></li>
            <li ><a  href="#skills" onclick="hideDiv()">Skills</a></li>
            <li ><a  href="#project" onclick="hideDiv()">Project</a></li>
            <li ><a  href="#contact" onclick="hideDiv()">Contact</a></li>
        </ul>
  • Related