Reputation: 404
I am trying to make a responsive menu with css html and a bit of jQuery , i used a checkbox with css to open or close the menu, also i want to close the menu when i click on any of the anchors, (it works) but if i click again on the menu icon to open it it works slowly every time until it takes too long to appear.
I think the problem are the click events but i don't know how to solve this.
thanks for your help
$(document).ready(function() {
click_events();
});
function click_events() {
$("#menu ul li a").click(function() {
$(this).parent().parent().parent().animate({
"margin-left": "-100%"
});
$("#btn-menu").prop("checked", false);
$("label").click(function() {
if ($("#btn-menu").prop("checked", true)) {
$("#menu").animate({
"margin-left": "0"
});
}
})
});
}
HTML
<header class="header">
<div class="container">
<div class="img-logo-container">
<img src="images/logo.png" alt="">
</div>
<input type="checkbox" id="btn-menu">
<label for="btn-menu"><i class="fas fa-bars"></i></label>
<nav class="menu" id="menu">
<ul>
<li><a href="#episodes">Episodios</a></li>
<li><a href="#invited">Invitados</a></li>
<li><a href="#topics">Temas</a></li>
<li><a href="#new">Novedades</a></li>
</ul>
</nav>
</div>
</header>
CSS
@media screen and (max-width: 991px) {
header label {
display: block;
}
header nav {
position: fixed;
background: #ffffff;
z-index: 1000;
width: 100%;
left: 0;
top: 70px;
height: 100vh;
overflow-y: auto;
margin-left: -100%;
}
#btn-menu:checked~.menu {
margin-left: 0;
transition: 0;
}
#btn-menu:not(:checked)~.menu {
margin-left: -100%;
transition: 0;
}
header nav ul li {
display: block;
text-align: center;
border-bottom: 1px solid black;
padding: 20px 0;
margin-left: 15px;
margin-right: 15px;
}
#btn-menu:checked~.menu {
display: block;
width: 100%;
}
}
Upvotes: 0
Views: 74
Reputation: 29239
This is happening because you bind the label
's click
event each time you click #menu ul li a
. The solution will be to move the the binding out of the click handler
.
So instead of
function click_events() {
$("#menu ul li a").click(function() {
$(this).parent().parent().parent().animate({
"margin-left": "-100%"
});
$("#btn-menu").prop("checked", false);
$("label").click(function() {
if ($("#btn-menu").prop("checked", true)) {
$("#menu").animate({
"margin-left": "0"
});
}
})
});
}
It should be
function click_events() {
$("#menu ul li a").click(function() {
$(this).parent().parent().parent().animate({
"margin-left": "-100%"
});
$("#btn-menu").prop("checked", false);
});
$("label").click(function() {
if ($("#btn-menu").prop("checked", true)) {
$("#menu").animate({
"margin-left": "0"
});
}
})
}
Upvotes: 1