Here is the code I wrote, and I tried to modify it but couldn’t find the right solution for my problem
<!-- Main content -->
<main>
<p>
Click the menu button in the top right corner to see the menu items.
</p>
<!-- Pop-up message -->
<div id="pop-up">
<p>Hello there!</p>
</div>
</main>
<script>
const menuButton = document.getElementById("menu-button");
const menuItems = document.getElementById("menu-items");
const popUp = document.getElementById("pop-up");
menuButton.addEventListener("click", function () {
if (menuItems.style.display === "none") {
menuItems.style.display = "block";
} else {
menuItems.style.display = "none";
}
});
document.addEventListener("click", function (event) {
if (
event.target !== menuButton && event.target !== menuItems
) {
popUp.style.display = "block";
}
});
need help that this code should work if it is correct and need to hide the menu bar
2
Answers
The issue that you are having is because the target itself is probably no the menu items, is one of the childrens. You can check if is the children with .contains() Here is a example using your code
You can add
event.stopPropagation()
to your list of menus to avoid triggering the event when clicked.Based on your code: