4

I have created some code which will hide/unhide a hidden div when a div("button") is clicked. I would also like the div to be hidden when anywhere on the screen is clicked. These pieces of code seem to be conflicting with each other.

$(document).ready(function () {

    $(document).on("click", "#help-icon", function () {
        console.log('hi');
        $("#help-menu").toggle();
    });

    $(document).mouseup(function (e) {
        var hlpcont = $("#help-menu");
        if (!hlpcont.is(e.target) && 
            hlpcont.has(e.target).length === 0) {
            hlpcont.hide();
        }
    });

});

jsfiddle: http://jsfiddle.net/CEs4c/1/

2
  • 10
    You forgot to put your HTML in your fiddle.
    – j08691
    Apr 15, 2014 at 18:49
  • 1
    so, what is the problem? the jsfiddle seems to be working fine for me. I click the button and it opens the div, i click anywhere (but the div itself and the button) and it closes. Apr 15, 2014 at 19:02

2 Answers 2

2
$(document).click(function (eventObj) {
    if (eventObj.target.id != "help-icon") {
        $("#help-menu").hide();
    } else {
        $("#help-menu").toggle();
    }
});

EDIT: If you want to click on the div that appears without hiding it again:

$(document).click(function(eventObj)
{
    if (eventObj.target.id == "help-icon") {
        $("#help-menu").toggle();
    } else if($(eventObj.target).hasClass("help-dropdown"))  {
        $("#help-menu").show();
    } else {
        $("#help-menu").hide();
    }


});
2
  • This will actually close the div which appears if clicked inside of it Apr 15, 2014 at 19:15
  • I edited my response to include a case where you don't want the appearing div to disappear if you click inside of it
    – shadowfox
    Apr 15, 2014 at 19:20
1

In my test, the mouseup function fires before the click function. The mouseup function checks for the target of the event. When you click on the button, the target of the mouseup event is the button, so the mouseup function hides the div, then the click function fires and toggles the div back to visible.

What I would do instead is just check the target of the event in mouseup and skip the click event:

$(document).mouseup(function (e)
    {
        var hlpcont = $("#help-menu");
        var hlpIcon = $("#help-icon");
        if(hlpIcon.is(e.target)){
            hlpcont.toggle();
        }else
            {
              hlpcont.hide(); 
            }

    });

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