Javascript / jQuery 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 ?
0
give a positive ratinggive a negative rating
18 Sep 2020 at 03:50 PM
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>

0
give a positive ratinggive a negative rating
20 Sep 2020 at 01:40 PM
Tim
This code works well on Windows and also Mac laptops, but it doesn't work on some Android mobile phones and iPhones. The menu appears on click, but it will not hide when I click outside. Have you got any idea why there is a problem with hiding of menu on some mobile web browsers ?
0
give a positive ratinggive a negative rating
22 Nov 2020 at 01:19 PM
Instead of javascript solution, you can try jQuery to show the menu on click and hide it on click outside. The solution below should be supported in iPhones and also in more Android phone web browsers. It is checking the class name of element that was clicked.


$(document).click(function(t){
var clicked = t.target.className;
if( ( clicked != "menu" ) ) {
$(".sub_menu").slideUp('slow').hide();
}
});

0
give a positive ratinggive a negative rating
22 Nov 2020 at 04:12 PM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us