I want to make a dropdown menu like the one in this site. I want to make 3 things happen.
- Make dropdown appear on click.
- Only display one dropdown at a time, so clicking on another dropdown link will remove the displaying dropdown and add the dropdown you clicked on.
- Removing displayed dropdown when clicking on the same dropdown link or clicking outside the dropdown.
I am not sure if I need a plugin or if the best way is to create this by writing your own code.
Here is my code and it works good but the only problem is that it dosen't remove the displayed dropdown when clicking on the same dropdown link.
$('a#menu1').click(function() {
$("div#1").show();
});
$('a#menu2').click(function() {
$("div#2").show();
});
$('a#menu3').click(function() {
$("div#3").show();
});
$(document).mouseup(function (e)
{
var container = new Array();
container.push($('.display_menu1'));
container.push($('.display_menu2'));
container.push($('.display_menu3'));
$.each(container, function(key, value) {
if (!$(value).is(e.target) // if the target of the click isn't the container...
&& $(value).has(e.target).length === 0) // ... nor a descendant of the container
{
$(value).hide();
}
});
});
div.body {
background-color: white;
width: 100%;
height: 400px;
border: 1px solid grey;
}
div.display_menu1 {
display: none;
}
div.display_menu2 {
display: none;
}
div.display_menu3 {
display: none;
}
ul {
margin: 0 0 30px 0;
padding: 0px;
}
li {
display: inline-block;
}
a.display {
display: inline-block;
background-color: lightblue;
padding: 10px 20px;
text-decoration: none;
}
div.display {
background-color: grey;
width: 200px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="body">
<ul>
<li>
<a href="#" method="POST" id='menu1' class="number">Menu 1</a>
</li>
<li>
<a href="#" method="POST" id='menu2' class="number">Menu 2</a>
</li>
<li>
<a href="#" method="POST" id='menu3' class="number">Menu 3</a>
</li>
</ul>
<div id="1" class="display display_menu1">
This is dropdown-menu 1!
</div>
<div id="2" class="display display_menu2">
This is dropdown-menu 2!
</div>
<div id="3" class="display display_menu3">
This is dropdown-menu 3!
</div>
</div>
</body>