Javascript menu - show on click and hide on click outside

I need to create a dropdown menu that will show on click and will hide on click outside. How can do it by using Javascript ?
posted on 18.09.2020 at 15:50
0pnshow more
StorStor
Hi,

To show the menu and close it when user clicks outside, you can use the simple solution below. It is based on javascript function target.


<script type="text/javascript">

window.onclick = function(event) {
if ( (!event.target.matches('.sub_menu')) && (!event.target.matches('.menu')) ) {
document.getElementById('sub').style.display='none';
}
}

</script>


<style>

.menu {
display: block;
text-decoration: none;
font-family: Arial;
color: #FFFFFF;
font-size: 12pt;
width: 150px;
background-color: #000080;
padding: 15px 0px 15px 0px;
width: 150px;
text-align: center;
}

.sub_menu {
display: none;
position: absolute;
}

.sub_menu_link {
display: block;
text-decoration: none;
font-family: Arial;
color: navy;
font-size: 12pt;
width: 150px;
background-color: #E6E6FF;
padding: 15px 0px 15px 15px;
}

a.sub_menu_link:hover {
display: block;
text-decoration: none;
font-family: Arial;
color: navy;
font-size: 12pt;
width: 150px;
background-color: #CCCCFF;
padding: 15px 0px 15px 15px;
}

</style>


<body>

<br />
<br />
<a href="javascript: void(0);" onClick="javascript: document.getElementById('sub').style.display='block';" class="menu" >Menu</a>
<div id="sub" class="sub_menu">
<a href="#1" class="sub_menu_link">Link 1</a>
<a href="#2" class="sub_menu_link">Link 2</a>
<a href="#3" class="sub_menu_link">Link 3</a>
</div>
<br />
<br />

</body>

posted on 20.09.2020 at 13:40
0pnshow more
TimTim
share on facebookshare on twitter
2020 AnswerTabsTermsContact us
This site uses cookies to improve your experience, for analytics and ads. By continuing to browse this site you agree to our use of cookies.