Reputation: 1111
I'm trying to fix my code for a responsive menu. The problem is whenever when I click on the About menu/button. The sub-menu for the gallery appears and not the about sub-menu. Here is the code I'm working on at the moment
HTML
<div class="container12">
<div class="column12">
<nav>
<ul>
<li><a href="#">Home</a></li>
<li>
<a href="#">Gallery</a>
<ul class="sub-menu">
<li><a href="#">Gallery1</a></li>
<li><a href="#">Gallery2</a></li>
</ul>
</li>
<li>
<a href="#">About</a>
<ul class="sub-menu">
<li><a href="#">About3</a></li>
<li><a href="#">About4</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</div>
</div>
JAVASCRIPT
<script>
$(document).ready(function(){
$('ul.sub-menu').hide(function(){
$('nav ul li').click(function(){
$('ul.sub-menu').slideToggle(500);
})
})
})
</script>
CSS
nav{margin-top:10px; display:block;}
nav ul li{display:inline; background-color:beige; float:left}
nav ul li a{display:inline-block; text-decoration:none; padding:10px 20px; position:relative}
.display_menu{display:block !important}
ul.sub-menu{position:absolute; display:none}
ul.sub-menu li{display:block; float:none }
@media only screen and (max-width: 360px){
nav ul li{display:block; float:none}
ul.sub-menu{position:static;}
}
Upvotes: 0
Views: 230
Reputation: 140
See an updated JSfiddle here
Your Javascript was looking for the first ul.submenu
in the tree of elements, which is the Gallery ul.sub-menu
. You need to tell it to look for the ul.sub-menu
as a child to the li
that you just clicked:
$('nav ul li').click(function(){
$('ul.sub-menu', this).slideToggle(500); // 'this' looks at what you just clicked
});
You also had your hide()
function to hide all the ul.sub-menu
's on the page surrounding the function to show your sub menu. This means when you click to show a sub menu, it would show it, then hide it immediately afterwards. I changed that to a solo function which hides all of the sub menus on document load only. Here is what you JS should look like now:
$(document).ready(function(){
$('ul.sub-menu').hide();
$('nav ul li').click(function(){
$('ul.sub-menu', this).slideToggle(500);
});
});
Upvotes: 1
Reputation: 1155
Your problem is that your event handler is causing all ul.sub-menu items to slide down. You need to specify that you only want the children of the element clicked to slide down:
<script>
$(document).ready(function(){
$('ul.sub-menu').hide(function(){
$('nav ul li').click(function(){
$(this).children('ul.sub-menu').slideToggle(500);
})
})
})
</script>
The line I changed is $(this).children('ul.sub-menu').slideToggle(500);
. In the event handler, this
refers to the element that triggered the event and the children
function finds its descendants filtered by the ul.sub-menu criteria.
Upvotes: 2