Reputation: 1120
I want to click a specific div and display a div containing child elements, then when clicking outside of that div and its child elements, the div and its child elements will be set to 'display: none' again. The following code does not work when clicking on child elements of the displayed div, and thus results in hiding the parent div. How do I include all child divs within event.target.id == 'menu-container' in the following code?
<body>
<div id = "screen">
<div id = "menu-container">
<li class = "menu-options">
<ul>option-1</ul>
<ul>option-2</ul>
<ul>option-3</ul>
</li>
</div>
<div id = "bottom-panel">
<div id = "menu-button">
CLICK HERE FOR MENU
</div>
</div>
</div>
<body>
The JQuery
$(document).ready(function() {
$('body').click(function(event){
if ( event.target.id == 'menu-button'){
$("#menu-container").show();
}else if(event.target.id == 'menu-container'){
return true;
}else{
$('#menu-container').hide();
}
});
});
Upvotes: 4
Views: 9290
Reputation: 33674
Here is the fiddle.
$(document).ready(function() {
$('body').click(function(event){
if ( event.target.id == 'menu-button'){
$("#menu-container").show();
}
else if (event.target.id == 'menu-container' ||
$(event.target).parents('#menu-container').length > 0)
{
return true;
} else {
$('#menu-container').hide();
}
});
});
Also you should correct your list, it should be:
<ul class="menu-options">
<li>option-1</li>
<li>option-2</li>
<li>option-3</li>
</ul>
Upvotes: 4
Reputation: 1138
You can add an boolean to check if your menu id open or not, like this.
$(document).ready(function() {
$('body').click(function(event){
console.log(event.target);
if (event.target.id == 'menu-button'){
$("#menu-container").show();
}else if($(event.target).hasClass("menu")){
return true;
}else{
$('#menu-container').hide();
}
});
});
Also, your HTML code seems incorret to me, i would use:
<ul class = "menu-options">
<li class="menu">option-1</li>
<li class="menu">option-2</li>
<li class="menu">option-3</li>
</ul>
Upvotes: 0