Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Anonymous

I am using this code:

$('body').click(function() {
   $('.form_wrapper').hide();
});

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

And this HTML:

<div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

The problem is that I have links inside the div and when they no longer work when clicked.

Solution

Had the same problem, came up with this easy solution. It’s even working recursive:

$(document).mouseup(function(e) 
{
    var container = $("YOUR CONTAINER SELECTOR");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});
Answered By: user659025

Related Articles

  • After a little scroll, the sticky navbar just is not fixed…
  • easiest way to extract Oracle form xml format data
  • jQuery Mobile: document ready vs. page events
  • how to use canvas in JavaScript flappy bird code
  • MouseUp and DoubleClick both attached to seperate event…
  • Issue with iron-ajax request
  • why preventdefault/stopPropagation not working in…
  • Vue stopPropagation not working - child to parent
  • XSLT generic solution to get hierarchical html table out of…
  • How do i update a javascript variable as its value changes?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I disable right click on my web page?

Next Post:

How to connect to SQL Server database from JavaScript in the browser?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error