Good day everyone!
I will admit right off the hop that I know very little about javascript programming but I hope that with your help, I can learn something today. I've looked on w3 and elsewhere to find my answer but I have not been successful. I think what I'm trying to do is simple...
Using w3.css, I am trying to create a navigation menu that will include more than one dropdown menu. I have the menu working to a point. Right now if I click on the three links with sub menus, the sub menus will display. However, they do not 'hide' unless I click on the top-menu link. That is, if I click on 'Training', the sub menu appears but will only disappear if I click on 'Training' again. Of course I want the sub-menu to disappear if I click anywhere outside the sub-menu or have another sub-menu appear if I click on its top-menu link.
I've attached my html file for you to have a look.
Any help and guidance would be greatly appreciated.
Thanks so much! Have a great day!
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<body>
<div class="w3-container">
<ul class="w3-navbar w3-light-grey">
<li><a href="#">Home</a></li>
<li class="w3-dropdown-click">
<a onclick="myFunction()" href="#">Manuals <i class="fa fa-caret-down"></i></a>
<div id="sub-menu" class="w3-dropdown-content w3-white w3-card-4">
<a href="#">Power Unit/Truck/Bus Safety Inspections and Standards</a>
<a href="#">School Bus Safety Inspections and Standards</a>
<a href="#">Trailer/Semi-Trailer Safety Inspections and Standards</a>
<a href="#">Motorcycle Safety Inspections and Standards</a>
</div>
</li>
<li class="w3-dropdown-click">
<a onclick="myFunction2()" href="#">Forms <i class="fa fa-caret-down"></i></a>
<div id="sub-menu2" class="w3-dropdown-content w3-white w3-card-4">
<a href="#">Supply Form</a>
<a href="#">Backup Forms</a>
<a href="#">Station Application</a>
</div>
</li>
<li class="w3-dropdown-click">
<a onclick="myFunction3()" href="#">Training <i class="fa fa-caret-down"></i></a>
<div id="sub-menu3" class="w3-dropdown-content w3-white w3-card-4">
<a href="#">Option 1</a>
<a href="#">Option 2</a>
<a href="#">Option 3</a>
</div>
</li>
<li><a href="#">Who to Call</a></li>
</ul>
</div>
<script>
function myFunction() {
var x = document.getElementById("sub-menu");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
}else {
x.className = x.className.replace(" w3-show", "");
}
}
function myFunction2() {
var x = document.getElementById("sub-menu2");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
}else {
x.className = x.className.replace(" w3-show", "");
}
}
function myFunction3() {
var x = document.getElementById("sub-menu3");
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
}else {
x.className = x.className.replace(" w3-show", "");
}
}
</script>
</body>
</html>
test.html