Reputation: 3
$(document).ready(function() {
$(".menu").click(function() {
$(".almenu").css("display", "block");
});
$(".almenu li a").click(function() {
$(".almenu").css("display", "none");
});
});
ul {
list-style: none;
}
a {
text-decoration: none;
display: block;
}
.almenu {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<ul>
<li class="menu" id="furas"><a href="#">Furas</a>
<ul class="almenu" id="furas_2">
<li><a href="#">Mely</a></li>
<li><a href="#">Kozpont</a></li>
</ul>
</li>
</ul>
</body>
When i click on "Furas" menu, the submenu appears. However, if I click on any submenu it does not hide.
Could you help me to understand the issue? Thanks!
Upvotes: 0
Views: 41
Reputation: 29277
That's because when the user clicks on the submenu it fires also the $(".menu").click
handler (because .menu
is its parent so it basically click
ed too).
In order to stop this, call to e.stopPropagation()
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$(document).ready(function() {
$(".menu").click(function() {
$(".almenu").css("display", "block");
});
$(".almenu li a").click(function(e) {
e.stopPropagation();
$(".almenu").css("display", "none");
});
});
ul {
list-style: none;
}
a {
text-decoration: none;
display: block;
}
.almenu {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="menu" id="furas"><a href="#">Furas</a>
<ul class="almenu" id="furas_2">
<li><a href="#">Mely</a></li>
<li><a href="#">Kozpont</a></li>
</ul>
</li>
</ul>
Upvotes: 2