As a JavaScript beginner, I decided to create an accordion menu using JavaScript. Although I was successful in implementing it, I encountered a bug in my program.
In this scenario, uppercase letters represent first-level menus while lowercase letters represent second-level menus.
The condition I wish to apply is as follows:
If A has children, clicking on A should display "a b c d".
If A does not have children, then the click on A should simply navigate to the linked page.
I am currently facing a roadblock where the implementation works slightly differently than intended:
If A has children, when clicked on A, it shows "a b c d". If A does not have children, A is not clickable.
Below you can find the source code:
MyJSFile.js
$(document).ready(function(){
$("#nav > li > a").on("click", function(e){
if($(this).parent().has("ul")) {
e.preventDefault();
}
if(!$(this).hasClass("open")) {
// hide any open menus and remove all other classes
$("#nav li ul").slideUp(350);
$("#nav li a").removeClass("open");
// open our new menu and add the open class
$(this).next("ul").slideDown(350);
$(this).addClass("open");
}
else if($(this).hasClass("open")) {
$(this).removeClass("open");
$(this).next("ul").slideUp(350);
}
});
});
Here is my CSS class MyCSS.css
#nav {
padding-left:0px;
display: block;
width: 100%;
margin: 0 auto;
}
#nav li {
list-style-type: none;
}
#nav > li > a:hover, #nav > li > a.open {
color: #FFF;
background-color: #38454B;
background-image: -webkit-gradient(
linear,
left top,
left bottom,
color-stop(0.35, #212121),
color-stop(1, #866F4A));
background-image: -o-linear-gradient(bottom, #212121 35%, #866F4A 100%);
background-image: -moz-linear-gradient(bottom, #212121 35%, #866F4A 100%);
background-image: -webkit-linear-gradient(bottom, #212121 35%, #866F4A 100%);
background-image: -ms-linear-gradient(bottom, #212121 35%, #866F4A 100%);
background-image: linear-gradient(to bottom, #212121 35%, #866F4A 100%);
}
#nav li ul {
display: none;
background-color: #CCC;
list-style-type: none;
}
Here is the HTML nav
<nav>
<ul id="nav">
<li><a href="">Home</a></li>
<li><a href="Go to page 1">Podiatry</a>
<ul>
<li><a href="Go to page 2.1">Overview</a></li>
<li><a href="">*Podiatric Diabetes</a></li>
<li><a href="">*Pediatric Podiatry</a></li>
<li><a href="">*Sports Podiatry</a></li>
<li><a href="Go to page 2.3">Tips from the podiatrist</a></li>
</ul>
</li>
<li><a href="index.php?country=US&page=contact">Contacts</a>
<ul>
<li><a href="http:/www.google.com/search?q=web+design+icons">Link 1</a></li>
<li><a href="http:/www.google.com/search?q=web+design+tutorials">Link 2</a></li>
<li><a href="http:/www.google.com/search?q=web+design+user+interface">Link 3</a></li>
<li><a href="http:/www.google.com/search?q=web+design">Link 4</a></li>
</ul>
</li>
</ul>
</nav>
Third party edit:
Check out the JSFiddle link for the code: http://jsfiddle.net/3STdc/