0

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.

Community
  • 1
  • 1
scrollup
  • 206
  • 4
  • 12

1 Answers1

1

Events bubble to parents also.

You can prevent this by using event.stopPropagation()

$('.trig').click(function (e) {
    e.stopPropagation();
    $('.menu').show();
    $('body').click( function () {
        alert('boo');    
    });
});

Since you are adding a click handler to the body before the event is over it is also being triggered on the body

Reference: https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thanks. I'm aware of event propagation. But what you helped me understand is that while the original event is executing any other events created there that are higher up the DOM can get excuted as well. – scrollup Nov 23 '14 at 16:24
  • yeah, it's not really intuitive behavior – charlietfl Nov 23 '14 at 16:25
  • I've came across this issue again, with a requirement that the inner listener should affect the elements of the outer listener. But if it was always prevented from propagating then it wouldn't work. So I created a var that gets set the first time and is used to determine if it should stop propagating. See here http://jsfiddle.net/srga8hzk/4/ – scrollup May 20 '15 at 20:36