How to find click outside an element using jQuery.

Finding Click outside an element is quite easy. We need to register click event for the whole window then prevent the click on the specified element using event.stopPropagation()

  • To find the click event outside an element we must attach a click to the document.

  • Then we need to register a click event to the specific element in which we need to prevent click.

  • To prevent click on the element we must use event.stopPropagation();

Sample code:

$(window).click(function() {
 //Hide the menus, opopup or any active element if visible.
});
$('#menucontainer').click(function(event) {
   event.stopPropagation();
});

Usage:

Finding click outside an element is most helpful to hide an active popup or active menu item on clicking elements except the active items.

Category: