In this tutorial, I’m gonna demonstrate you how to track if a click event is being made outside of an HTML element.
Through this example, we are going to close or hide div using Jquery when a click action occurs outside of that element on which the DIV was produced by clicking.
If you have ever found with menus boxes that open on click event, but want them to close when a click event occurs outside of that dom elements.
Here is a simple way to do so. I’m gonna add an event listener to the document’s body. When someone clicks it, we look for the event’s targeted id. If the ID is same as the box’s div, then we do nothing, if it doesn’t, we fadeOut the menu box.
How to hide div when clicking outside
$(document).mouseup(function (e){
var container = $("#YOUR_TARGETED_ELEMENT_ID");
if (!container.is(e.target) && container.has(e.target).length === 0){
container.fadeOut();
}
});
Note: don’t forget to change YOUR_TARGETED_ELEMENT_ID
with your targeted element’s ID.
We are using Jquery’s fadeIn()
& fadeOut()
functions here to hide and show the box. If you want to use Javascript you can set the css property display block to show the box and display none to hide the box.
To learn more interesting Jquery tricks please subscribe us, and share this article.
You may also like
Please help us by showing your reaction
Thank you for this helpful tutorial! Why do we use “mouseup” instead of “click”?
Click Event Fires when a
mousedown
andmouseup
event occur on the same element.suppose someone mousedown at an element and mouseup at another element by dragging the cursor, it’ll create a little bug I guess.
However you can use Click event as well.
How to use class instead of id? Thanks
just use “.” insted of “#”
Thanks For Great. *****
Thank you for all your help. I was having so much trouble with this. Thank you thank you again.
If a click is first needed to open the layer and only then click to close. What code will be?
are you looking for some sort of modal?