简体   繁体   中英

Close responsive hamburger menu when clicking outside

Is it possible to close a hamburger menu when clicking outside of it? It takes too much space. So far I can close it when clicking the button again, but what if I also want to close it when clicking anywhere else on the page? Here's the code for the menu button:

const links = document.getElementById("links");

hamburger.addEventListener("click", () => {
    links.classList.toggle("show");
    hambuger.onclick()
});

In the HTML:

            <img id="IPtokiLOGOBlack" src="styles/images/IPtokiLOGOBlack.svg" />
            <button class="hamburger" id="hamburger">
                <i class="fa fa-bars"></i>
            </button>
            <div class="active" id="links">
                <a href="#home"><?=$menuHome ?></a>
                <a href="#about"><?=$menuAbout ?></a>
                <a href="#projects"><?=$menuProjects ?></a>
                <a href="#team"><?=$menuTeam ?></a>
                <a href="#contact"><?=$menuContact ?></a>
                <a href="#jobs"><?=$menuJobs ?></a>
                <?=$menuLanguage ()?>
            </div>
        </div>

I tried this but no success (doesn't even open here):

document.querySelectorAll(".hamburger").forEach((trigger) => {
    const menu = document.querySelector(trigger.dataset.menu);
    const hamburger = document.getElementById("hamburger");
    const links = document.getElementById("links");

    function open() {
        hamburger.addEventListener("click");
        links.classList.toggle("show");
    }

    function close() {
        menu.classList.remove("show");
        menu.removeEventListener("click", outsideClose);
    }

    function outsideClose(event) {
        if (event.target !== menu) {
            close();
        }
    }
    trigger.addEventListener("click", open);
});

在此处输入图片说明

I don't know exactly what is the missing code, but this can be done using element.contains() method:

function outsideClose(event)) {
    if (!menu.contains(event.target) {
        close();
    }
}

// assuming this is how outsideClose would look like:

function open() {
    hamburger.addEventListener("click");
    links.classList.toggle("show");

    window.addEventListener('mousedown', outsideClose);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM