Reputation: 513
I have a dropdown menu. I want it to be dynamic so I can only tell a li
(in the nav
) that it is a dropdown and then give it a list afterwards that is dropdown content. The problem is that when you click on a link with the .dropdown
class it shows all elements with the .dropdown-content
class. Any idea of a smart selector that would work here?
My HTML:
<li><a class="dropdown" href="#">Gallery</a>
<ul class="dropdown-content">
<li><a href="#">Photos on me</a></li>
<li><a href="#">Photos of me</a></li>
<li><a href="#">Photos with me</a></li>
</ul>
</li>
<li><a class="dropdown" href="#">Blog</a>
<ul class="dropdown-content">
<li><a href="#">Photos on me</a></li>
<li><a href="#">Photos of me</a></li>
<li><a href="#">Photos with me</a></li>
</ul>
</li>
My js:
var main = function() {
$('.dropdown').click(function(){
$('.dropdown + .dropdown-content').toggle(200);
});
}
Upvotes: 0
Views: 132
Reputation: 194
Just include data
and id
to your code. This will resolve your problem.
JS Bin on jsbin.com
(function() {
$('.dropdown').click(function(e){
var id = $(this).data('toggle');
$('#' + id).toggle();
});
}());
.dropdown-content {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<ul>
<li><a class="dropdown" href="#" data-toggle="first">Gallery</a>
<ul class="dropdown-content" id="first">
<li><a href="#">Photos on me</a></li>
<li><a href="#">Photos of me</a></li>
<li><a href="#">Photos with me</a></li>
</ul>
</li>
<li><a class="dropdown" href="#" data-toggle="second">Blog</a>
<ul class="dropdown-content" id="second">
<li><a href="#">Photos on me</a></li>
<li><a href="#">Photos of me</a></li>
<li><a href="#">Photos with me</a></li>
</ul>
</li>
</ul>
</body>
</html>
Upvotes: 0
Reputation: 690
Get the element on which click event has happened, and from that find the siblings class that you are looking for.
$('.dropdown').click(function(){
$(this).siblings('.dropdown-content').toggle(200);
});
OR
$('.dropdown').click(function(){
$(this).next().toggle(200);
});
Upvotes: 5