Here is a dropdown menu solution that I have implemented: http://jsfiddle.net/ftymhs8s/
The problem I am facing is that when I click on a different line, I want to hide the currently displayed dropdown menu and show the dropdown menu of the clicked line. Additionally, I want the dropdown menu of the first line to always be displayed when people visit the website.
I believe I have described my issue correctly. Can someone please assist me with this?
// Dropdown Menu
var dropdown = document.querySelectorAll('.dropdown');
var dropdownArray = Array.prototype.slice.call(dropdown, 0);
dropdownArray.forEach(function(el) {
var button = el.querySelector('a[data-toggle="dropdown"]'),
menu = el.querySelector('.dropdown-menu'),
arrow = button.querySelector('i.icon-arrow');
button.onclick = function(event) {
if (!menu.hasClass('show')) {
menu.classList.add('show');
menu.classList.remove('hide');
arrow.classList.add('open');
arrow.classList.remove('close');
event.preventDefault();
} else {
menu.classList.remove('show');
menu.classList.add('hide');
arrow.classList.remove('open');
arrow.classList.add('close');
event.preventDefault();
}
};
})
Element.prototype.hasClass = function(className) {
return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};
ul {
list-style: none
}
.dropdown a {
text-decoration: none;
}
.dropdown [data-toggle="dropdown"] {
position: relative;
display: block;
color: black;
padding: 10px;
}
.dropdown .dropdown-menu {
max-height: 0;
overflow: hidden;
}
.dropdown .dropdown-menu li {
padding: 0;
}
.dropdown .dropdown-menu li a {
display: block;
padding: 10px 10px;
}
.dropdown .show {
display: block;
max-height: 9999px;
margin-left: 50px;
}
.dropdown .hide {
max-height: 0;
}
<div class="container">
<ul>
<li class="dropdown">
<a href="#" data-toggle="dropdown">First Menu</a>
<ul class="dropdown-menu">
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown">Second Menu</a>
<ul class="dropdown-menu">
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown">Third Menu </a>
<ul class="dropdown-menu">
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</li>
</ul>
</div>