I am trying to make a submenu using jQuery. The idea is that when someone clicks on the first menu a submenu appears, then when someone clicks the submenu it disappears and shows a div with information but I cant make it work properly.
Here is my HTML:
<ul id="menu">
<li>
<a href="#">Item 1</a>
<ul id="submenu">
<li><a href="#" data-menu="show1">Sub menu 1</a></li>
<li><a href="#" data-menu="show2">Sub menu 2</a></li>
</ul>
</li>
</ul>
<div id="show1" class="content">Lorem ipsum ad his scripta blandit partiendo, eum fastidii accumsan euripidis in, eum liber hendrerit an. </div>
<div id="show2" class="content">Ius id vidit volumus mandamus, vide veritus democritum te nec, ei eos debet libris consulatu. No mei ferri </div>
And this is my jQuery:
$(document).ready(function () {
$('#menu li ').click(function () {
$('#submenu').fadeToggle();
$('.content').fadeOut();
});
$('ul#submenu li a').click(function () {
var menu = $(this).data("menu");
$('#' + menu).fadeIn();
});
});
The idea is simple, if menu is clicked all the content divs must hide and the submenu must toggle (show if hidden, hide if shown.) When a submenu item is clicked, the submenu must hide and the content div matching the data attribute clicked must appear.
But, when I click the submenu item it shows the content for a moment then it disappears. Any idea on what I am doing wrong?
Here is the fiddle: https://jsfiddle.net/yab34zdw/
When you click on a submenu item, both of those event handlers are being fired. The problem is with your selectors:
$('#menu li ')
also captures the submenu items, which are also <li>
tags that are descendants of the menu. You could just change the selector to $("#menu > li")
, which captures only direct descendants (children), but I think in general its just better to add classes, and use simpler selectors.
HTML
<ul id="menu">
<li class="menu-top-item>
<a class="menu-top-item-link" href="#">Item 1</a>
<ul id="submenu">
<li class="menu-sub-item">
<a class="menu-sub-item-link" href="#" data-menu="show1">Sub menu 1</a>
</li>
<li class="menu-sub-item">
<a class="menu-sub-item-link" href="#" data-menu="show2">Sub menu 2</a>
</li>
</ul>
</li>
</ul>
Javascript Fiddle
$('.menu-top-item-link').click(function () {
$('#submenu').fadeToggle();
$('.content').fadeOut();
return false;
});
$('.menu-sub-item-link').click(function () {
var menu = $(this).data("menu");
$('#' + menu).fadeIn();
return false;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With