I've tried searching for an explanation to my issue below but it's possible the keywords I used are to ambiguous.. so I turn to you.
I'm trying to implement a click outside menu to close based on this code here which is:
$('#menuscontainer').click(function(event) {
//your code that shows the menus fully
//now set up an event listener so that clicking anywhere outside will close the menu
$('html').click(function(event) {
//check up the tree of the click target to check whether user has clicked outside of menu
if ($(event.target).parents('#menuscontainer').length==0) {
// your code to hide menu
//this event listener has done its job so we can unbind it.
$(this).unbind(event);
}
})
});
However it seems the function in $('html').click...
gets executed when clicking on the #menucontainer
so it just open and immediately closes.
I've simplified it to:
$('.trig').click(function () {
$('.menu').show();
$('body').click( function () {
alert('boo');
});
});
Here's the JSFiddle link.
As you can see alert gets executed when .trig
is clicked on. So instead of just creating the even listener, it seems to already be listening.
Can someone please explain this to me? Thanks.