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/

KyleMit
  • 30,350
  • 66
  • 462
  • 664
user3032973
  • 415
  • 2
  • 8
  • 26
  • 10
    You forgot to put your HTML in your fiddle. – j08691 Apr 15 '14 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. – Federico Dorfman Apr 15 '14 at 19:02

2 Answers2

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


});
user3032973
  • 415
  • 2
  • 8
  • 26
shadowfox
  • 505
  • 4
  • 7
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(); 
            }

    });
Robert Munn
  • 778
  • 7
  • 12