1

I am having a bit of an issue with showing and hiding a menu using jQuery. What I am trying to do is:

If a button is pressed, then show a menu div. If the somewhere other than the div is clicked, hide the menu div.

Here's where my issue comes in. The above works perfectly, but when you click on an element which is inside of the div, the menu is hidden, which is not my intended outcome. My code is as follows:

$(document).ready(function() {
    $(document).click(function(e) {
        if (e.target.id != "projectEdit") {
            if (e.target.id != "projectEditMenu") {
                $("#projectEditMenu").hide();
            }
        } else {
            $("#projectEditMenu").show();
        }
    });
});

How can I make it so that if the children of the menu div were excluded from this argument, it keeps the menu open if the children are clicked on?

HTML code:

    <div id="projectEditMenu">

        <div id="projectEditMenuMarker"></div>

        <div id="projectEditMenuAddTile">

            <span id="projectEditMenuAddTileTitle">Add Tile</span>

            <form id="newTileForm" action="openProject.php" method="put" hidden></form>

            <input form="newTileForm" type="text" name="newTileName" id="newTileNameInput" placeholder="Tile Name">

        </div>

    </div>
halfer
  • 19,824
  • 17
  • 99
  • 186
Ryan
  • 1,096
  • 2
  • 16
  • 31

3 Answers3

9

You can use closest() which will include descendents of the selector passed as argument and the element itself

Example:

$(document).click(function (e) {
     var $tgt = $(e.target);
    if ($tgt.closest("#projectEdit").length) {
        alert('I am part of "#projectEdit"');
    }   

});

closest() API Docs

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

Try this:

var textArea = $('#textarea');

textArea.click(function() {

    textArea.addClass('selected');

});

$('body').click(function(e){

    if( textArea.is('.selected') &&
        !$(e.target).is(textArea)){

        textArea.removeClass('selected');

    }

});
Caio Kawasaki
  • 2,894
  • 6
  • 33
  • 69
0

Another solution

$(document).ready(function() {
    var in_menu = false;
    $('#projectEdit').click(function() {
        in_menu = false;
        $("#projectEditMenu").show();
        $('#projectEditMenu').hover(function() {
            in_menu = true;
        }, function() { 
            in_menu = false;
        });
        $('html').click(function() {
            if( !in_menu ) { 
                $("#projectEditMenu").hide();
                //delete all events
                $('#projectEditMenu').unbind();
                $('html').unbind('click');
            }
        });
    });
});
Thibault Bach
  • 558
  • 5
  • 8