How to customize div id including all child elements in JQuery

I want to click on a specific div and display a div that contains children, and then by clicking outside of that div and its children, the div and its children will be set to "display: none" again. The following code does not work when the children of the displayed div are clicked and hence causes the parent div to be hidden. How can I include all child divs in 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>

      

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();
    }
});
});

      

http://jsfiddle.net/ecABg/

+3


source to share


2 answers


Here is a 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>

      

+4


source


You can add a boolean to check if your menu id is open eg.

$(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 seems out of place 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>

      

0


source







All Articles