I’m facing the problem with the burger menu. I want to make it disappear after clicking on the menu position and away of the menu as well. I am a beginner. Thanks in advance.
CSS
.burger {
display: block;
transition: 0.3s ease-out;
}
.burger.active .line:first-child {
transform: translateX(+300px);
}
#menu {
display: flex;
position: absolute;
right: 0;
flex-direction: column;
top: 100px;
height: 400px;
text-align: center;
width: 75%;
z-index: 1;
transform: translateX(100%);
transition: 0.3s ease-out;
}
#menu.active {
transform: translateX(0%);
transition: 0.3s ease-out;
}
#menu li {
font-weight: 500;
font-size: 28px;
line-height: normal;
}
#menu li a {
color: #ffffff;
text-decoration: none;
}
Javascript
document.querySelectorAll(".filterable_cards img").forEach((image) => {
image.onclick = () => {
document.querySelector(".popup-image").style.display = "block";
document.querySelector(".popup-image img").src =
image.getAttribute("src");
};
});
HTML
<ul id="menu">
<li><a href="#home">Home</a></li>
<li><a href="#about">O mnie</a></li>
<li><a href="#graphics">Grafika</a></li>
<li><a href="#contact">Kontakt</a></li>
</ul>
<div class="burger">
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
</div>
Mostly I need a help with the Javascript code I think.
2
Answers
It seems you want to hide the burger menu after clicking a menu item. You may need to add an event listener on each menu item and toggle the
active
class when menu items are clicked. Here’s how you can do this:You can also hide the menu when you click outside:
The above code will track a click event on each menu item. When a click event is detected, it will remove the active class from the menu and hamburger button, causing them to hide. The changes in the
.active
class will affect the CSS transform property, providing a slide-in/slide-out animation.I recommend adding this JavaScript code to the end of your HTML body tag or placing it inside a function that is called after the
DOMContentLoaded
event, to ensure all elements have been rendered to the DOM before the script is run.All my best in your learning journey.