jacobdo jacobdo - 27 days ago 9
Javascript Question

binding event on click

I have a context menu button and a context menu, that opens whenever the context menu button is clicked. On this very click I also want to bind an event on the document so that the context menu collapses if the next click is outside the boundaries of the context menu, however, with my code the second event logic is executed already when the context menu opens.

$('.btn-user-context-menu').on('click tap', function(){

//open the menu
$('.context-menu[data-context="user"]').toggleClass('open');

//bind event so that menu collapses if next click is outside of it
$(document).on('click tap', function(e){
console.log('x');
})
})


Thank you for your help and I would really appreciate an explanation as well :)

Answer

Attach a click event to the document body which closes the window. Attach a separate click event to the window which stops propagation to the document body.

$(window).click(function() {
//Hide the menus if visible
});

$('.btn-user-context-menu').click(function(event){
    event.stopPropagation();
});

Source: answer

(I don't have enough rep to leave a comment)