Explain Codes LogoExplain Codes Logo

Use jQuery to hide a DIV when the user clicks outside of it

javascript
event-delegation
click-handling
responsive-design
Nikita BarsukovbyNikita Barsukov·Mar 9, 2025
TLDR

If you're clicking outside a div and want it to vanish faster than last year's New Year's resolution, here's a quick jQuery solution. Use event.stopPropagation() inside your div's click handler to make sure the click event doesn't escape to the wild, aka the document:

$(document).click(function() { $("#yourDiv").hide(); // Hide div when you click anywhere on the document }); $("#yourDiv").click(function(event){ event.stopPropagation(); // This div's got thick walls. Clicks can't escape! });

Clicking anywhere outside #yourDiv triggers the hide function, while an inside click acts like it hit a brick wall, thanks to event containment.

From basic to advanced: Enhancing the fast answer

Gracefully handling internal interactions

Although the fast answer gets the job done, let's fine-tune our approach to deal with more complex scenarios. For instance, your div might contain smaller elements like dropdown menus or other clickable items. We need to ensure these stay functional.

Play nice with dropdowns

Have a .dropdown in your div? Make sure the universe doesn't collapse (i.e., your div doesn't hide) when using it:

$(document).click(function(event) { if (!$(event.target).closest('.dropdown').length) { $("#yourDiv").hide(); // Prevent Armageddon (hiding the div) when accessing dropdowns } }); $("#yourDiv").click(function(event){ event.stopPropagation(); });

If your div is a little mini internet, complete with its own internal links, make sure you can still surf:

$("#yourDiv a").click(function(event) { if ($(this).hasClass('no-hide') || $(this).is('#specific-link')) { event.stopPropagation(); // Click me all you want, I won't hide the div } });

Avoid event overload

Are you attaching multiple event listeners like you're Santa Claus? That's going to put a lot of strain on the poor old web browser. Instead, act like a minimalist and use a single listener for document:

$(document).click(function(event) { var $target = $(event.target); if (!$target.closest('#yourDiv').length && !$target.is('#ignored-element')) { $('#yourDiv').hide(); // Who clicked where now? } });

You're basically using one handler to cover multiple bases. Efficient, right? In this setup, #ignored-element is an element that gets a free pass from the hiding action.

Closing the gap: from theory to practice

Delegated event handling: One handler to rule them all

If you're a fan of The Lord of the Rings, you're going to love event delegation. Much like the One Ring controls all others, a single event listener can handle all events from its children.

$('body').on('click', function(event) { if (!$(event.target).closest('#yourDiv').length) { $('#yourDiv').hide(); // One ring to rule them all } });

This method especially shines when your div strides onto the scene later, not at page load but dynamically.

Clarity above all: Keep your code well-organized

If there's one thing that developers value, it's clean, readable code. Keep your click handlers focused and clear of too many conditions. This isn't just about prettiness — it facilitates both readability and maintainability.

Don't forget the edge cases!

Remember, end users are basically Chaos from Sonic the Hedgehog — unpredictable. They might press the Tab key to navigate, interact with form elements, or use keyboard shortcuts. So, become a boy scout and be prepared. Attach additional listeners for keyboard events or focus changes and adjust your hide behavior accordingly.