Hide Container When Click Outside Target with jQuery

Hide a container div when you click outside of a target div within that container.


<div class="login-popup">

     <div class="login-popup__modal">
          <div class="login-popup__warning"><img src="<?php echo get_home_url(); ?>/wp-content/uploads/2019/06/times-octagon-solid.svg" alt="Warning Icon"></div>
          <?php if( $wd_option_login_modal_message ) : ?>
               <p class="login-popup__content"><?php echo $wd_option_login_modal_message; ?></p>
          <?php endif; ?>
          <?php if ( $wd_option_login_modal_link ) { ?>
          	<a href="<?php echo $wd_option_login_modal_link['url']; ?>" target="<?php echo $wd_option_login_modal_link['target']; ?>"><?php echo $wd_option_login_modal_link['title']; ?> →</a>
          <?php } ?>

          <img class="login-popup__logo" src="<?php echo get_home_url(); ?>/wp-content/uploads/2019/04/home-evexia-large-logo.png" alt="Evexia Logo">




jQuery(document).ready(function() {
     jQuery('.target-div a').click(function(e) {
jQuery(document).mouseup(function(e) {
    var container = jQuery('.login-popup__modal.active');
    // 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) {


About Matt Whiteley

Matt has been building bespoke WordPress websites for over 10 years specializing in the Genesis Framework. He integrates Advanced Custom Fields heavily in all builds, especially with the new Gutenberg Block Editor, allowing clients to easily modify all aspects of the their website with ease.

He works with a wide variety of small businesses and agencies across the country providing development services as well as hosting and maintenance. When he isn't coding he enjoys spending time with his wife and two children, golfing and playing poker.