Reputation: 157
I need some help. I try to create a toggle submenu, using jQuery. However, submenu appears only for a few seconds and then disappears, when I click the parent li
.
Here is the code:
<div class="menu">
<ul>
<li class="parent">
<a href="">Hello</a>
<ul class="submenu">
<li>
<a href="">Hello</a>
</li>
<li>
<a href="">Hello</a>
</li>
</ul>
</li>
<li class="parent">
<a href="">Hello</a>
<ul class="submenu">
<li>
<a href="">Hello</a>
</li>
<li>
<a href="">Hello</a>
</li>
</ul>
</li>
</ul>
</div>
And here is the jQuery code
$(function() {
$(".submenu").hide();
$(".parent").click(function(){
$(".submenu").toggle()
});
});
Upvotes: 0
Views: 2095
Reputation: 9637
Use this
for current selected element and find
the particular class inside the dom
$(function () {
$(".submenu").hide();
$(".parent").click(function (e) {
e.preventDefault(); // If you need to stop default action
$(".submenu", this).toggle(); // OR $(this).find(".submenu").toggle();
});
});
try as you asking in comment
$(function () {
$(".submenu").hide();
$(".parent").click(function (e) {
e.preventDefault();
if (!$(e.target).closest("ul").is(".submenu")) {
$(".submenu", this).toggle();
}
});
});
$(function () {
$(".submenu").hide();
$(".parent").click(function (e) {
e.preventDefault();
if (!$(e.target).closest("ul").is(".submenu")) {
$(".submenu", this).toggle();
$(this).siblings(".parent").find(".submenu").hide();
}
});
});
Upvotes: 1
Reputation: 67207
Try to pass this as the context to the selector,
$(function () {
$(".submenu").hide();
$(".parent").click(function (e) {
$(".submenu:first", this).toggle();
return false;
});
});
At this situation we need both .preventDefault()
as well as .stopPropagation()
needs to be invoked. So I recommend you to use return false
to perform both of that operations.
$(function () {
$(".parent a").click(function (e) {
var elems = $(this).closest('li');
if (elems.find('.submenu').length) {
$(".submenu:first", elems).toggle();
}
return false;
});
});
For your new requirement use the below code,
$(function () {
$(".submenu").hide();
$(".parent a").click(function (e) {
var elems = $(this).closest('li');
elems.siblings('li').find('ul').hide();
if (elems.find('.submenu').length) {
$(".submenu:first", elems).toggle();
}
return false;
});
});
Upvotes: 0