javascript - Detect click outside divs with particular class and hide them -


my dom looks this:

<div class = filter x>     <div class = a>         <ul><li>……..</li></ul>     </div> </div> <div class = filter y>     <div class = a>         <ul><li>……..</li></ul>       </div> </div> 

both divs class dropdown menus. expected functionality is:

  1. whenever click on divs class filter, js-active class added , dropdown opens.
  2. whenever click anywhere outside div or dropdown, js-active class removed , dropdown hides.
  3. at time, 1 out of 2 dropdowns open.

another event handling if 1 dropdown visible , click on dropdown, first 1 hides (remove class js-active)

i able achieve following code:

 $(document).on('mouseup touchend', function(e){        var xcontainer = $(‘.filter x’);        var ycontainer = $(‘.filter y’);        if (!xcontainer.is(e.target) && xcontainer.has(e.target).length === 0)           {               xcontainer.removeclass('js-active');           }        if (!ycontainer.is(e.target) && ycontainer.has(e.target).length === 0)           {               ycontainer.removeclass('js-active');           }  }); 

i want optimize code. tried using jquery "each" iterate on divs class filter , use same logic didn’t work expected. suggestions helpful. thanks.

there no need handle both x & y separately, can like

$(document).on('mouseup touchend', function(e) {    var $filter = $(e.target).closest('.filter');    if ($filter.length) {      $filter.addclass('active');    }    $('.filter.active').not($filter).removeclass('active');  });
.filter {    min-height: 20px;    background-color: lightgrey;    margin-bottom: 5px;  }  .filter .a {    display: none;  }  .filter.active .a {    display: block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="filter x">    <div class="a">      <ul>        <li>……..</li>      </ul>    </div>  </div>  <div class="filter y">    <div class="a">      <ul>        <li>……..</li>      </ul>    </div>  </div>  other content


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -