Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm having a ton of trouble trying to get simple jquery functionality to work. All I want is to be able to click on a menu button and have a menu pop up and click outside of it to close it. I think the problem may have to do with the parent to child structure of my code. Please offer any advice into what I may be doing wrong.

<div id = "outer-screen">
<div id = "screen-container">
  <div id = "screen">
        <div id = "menu-container">

        </div>
        <div id = "bottom-panel">
            <div id = "menu-button">
            Menu
            </div>
        </div>
  </div>
</div>

$("#menu-button").click(function(){
    $("#menu-container").show();
});

})

$('body').click(function(e){
if ( e.target.id == 'menu-container'){
    return true;            
}else{
     $('#menu-container').hide();
}
})
share|improve this question
3  
Hello, and thanks for your question. If the code does not work, it is unfortunately off-topic and should be posted on StackOverflow instead. Sorry for the hassle. –  Quentin Pradet Feb 12 '13 at 7:14
add comment

closed as off topic by Quentin Pradet, palacsint, Glenn Rogers, Brian Reichle, svick Feb 12 '13 at 11:15

Questions on Code Review Stack Exchange are expected to relate to code review request within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

up vote 2 down vote accepted

The $('body').click function will override the first function declaration (they might actually both get called but the function bound to the body's click event seems to take precedence), what this means is that when you click on #menu-button the menu-container will be shown and immediately hidden since you clicked outside it. Use the following

<script type="text/javascript">

$(document).click(function() {

    $('body').click(function(e){
        if ( e.target.id == 'menu-button'){
            $("#menu-container").show();
        }else if(e.target.id == 'menu-container'){
            return true;
        }else{
            $('#menu-container').hide();
        }
    });

});



</script>
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.