I’m trying to assign an function a click on the body after another element has been click. This is the code I’m using:
$('#myButton').click(function() {
$('body').on('click', closePopup);
});
closePopup = function() {
console.log('closePopup fired');
$('body').off('click', closePopup);
};
The desired result is that closePopup is assigned to the body only AFTER the myButton click. But what happens is that closePopup is fired immediately when myButton is clicked. Why is this happening?
That happens because events bubble. Once your event handler finishes handling the event on the button, it bubbles up to the body where the body then handles it. to prevent that, stop propagation of the event on the button click.
Note however that this will result in multiple events being bound if you click the button more than once. You can fix it by modifying it a bit more: