event.stopPropagation() on menu icon click event handler

With a menu icon that displays a menu list on click and hides menu when clicked again, you don't want any other click event listeners responding to the click on the menu icon. To prevent this, you would need to add "event.stopPropagation()" to the menu icon event handler.

Definition: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

This is especially needed when you have a click event listener on the document where whenever you click anywhere outside the menu list items, the menu list would close/hide. If there was no event.stopPropagation(), when you click on the menu icon, this listener on the document would respond and hide the menu list even though you are trying to display it.

$(".menu-items").hide(); //hide menu on page load

$(".menu").click(function() {
event.stopPropagation(); //so clicking menu icon does not trigger event listener on document to hide menu
if( $(".menu-items").is(":hidden") ) {
$(".menu-items").slideDown("500");
}
else if( $(".menu-items").is(":visible") ) {
$(".menu-items").slideUp("500");
}
});

//clicking anywhere outside list items would close the menu list
$(document).click(function(event) {
if( !$(event.target).closest(".menu-items li").length ) {
if( $(".menu-items").is(":visible") ) {
$(".menu-items").slideUp("500");
}
}
})

Comments

Popular posts from this blog

Code Wars: Data Reverse (6 kyu)

Code Wars: longest_palindrome (6 kyu)

Code Wars: Find the odd int