How do I detect a click outside an element?

In this post we will show you How do I detect a click outside an element?, hear for How do I detect a click outside an element? we will give you demo and example for implement.

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

Solution 1 : detect a click outside an element

if you click outside of div or your element it will notify you for out side click event.

$(window).click(function() {
	// Do your procsee or
	// Hide the menus/popup if it is visible
});

$('#YourDivId').click(function(event){
    event.stopPropagation();
});

NOTE: Using stopEventPropagation() is something that ought to be kept away from as it softens typical occasion stream up the DOM. See this article for more data. Consider utilizing this strategy.

Solution 2 : detect a click outside an element

if you click outside of div or your element it will notify you for out side click event.

if(!$(event.target).is('#YourDivId'))
{
	// Do your procsee or
	// Hide the menus/popup if it is visible
}

Solution 3 : detect a click outside an element

if you click outside of div or your element it will notify you for out side click event.

$('#YourDivId').click(function(event) {
	$('html').one('click',function() {
		// Do your procsee or
		// Hide the menus/popup if it is visible
	});
    event.stopPropagation();
});

Solution 4 : detect a click outside an element

$('html').click(function (e) {
    if (e.target.id == 'YourDivId') 
	{
        // Do your procsee for click
		// inside an element
    } 
	else 
	{
        // Do your procsee for click
		// outside an element
    }
});

Hope this code and post will helped you for implement How do I detect a click outside an element?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve onlincode. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs onlincode.org