Reputation: 21
Okay so i made drop down menu and i want it to be closed whenever user clicks anywhere at body.for this i need to attach some java Script code to body tag. i'm new to JavaScript and i have no idea how to do this. Is this even possible?
By the way, I found way of doing this with Jquery but i don't want to use it.
also giving me an example will be really useful.
thanks.
(ignore)
<script>
function show_menu(){
var menu = document.getElementById('dropdown_menu');
if(menu.style.display == 'block'){
menu.style.display = 'none';
}else {
menu.style.display = 'block';
}
}
</script>
Upvotes: 0
Views: 72
Reputation: 36794
Here's the basic idea. Hide the menu if the user clicks on the document, but stop event bubbling if the event target is the container. Also, if the menu is clicked, show the dropdown menu.
var menu = document.getElementById('container'), list = document.getElementById('dropdown_menu');
document.addEventListener('click', function(){
list.style.display = 'none';
});
menu.addEventListener('click', function(e){
list.style.display = 'block';
if(e && e.stopPropagation){ e.stopPropagation(); }
else {
e = window.event;
e.cancelBubble = true;
}
});
Upvotes: 1
Reputation: 944568
addEventListener
is a method on every element (among a few other things) and is the standard way to make a function run when "something" happens.
Call it on the body element, telling it what sort of event you want to react to and what function you want to run.
document.body.addEventListener('click', show_menu);
Upvotes: 2