Trigger a function when clicks outside of an element in jQuery

If you need to hide a div when you click outside of it. Below snippets are explaining that behavior in detail.
HTML

<div class="main-container">
<div> Hello I am the title</div>
<div class="tobehide">I will hide when you click outside of me</div>
</div>

 

jQuery 

jQuery(document).click(function(e) {
var target = e.target; //target div recorded
if (!jQuery(target).is('#tobehide') ) {
jQuery(this).fadeOut(); //if the click element is not the above id will hide
}
})

Its pretty self explanatory, when you click outside of the target div, the jQuery function check for then click event is based on the element. If not the div will fade out.

Editorial Staff
 

Editorial Staff at tutsplanet is a dedicated team to write various tutorial articles.