jeff jeff - 1 month ago 6
HTML Question

Closing all other DIVS while opening one

What I am trying to achieve is the following


  1. There are two DIVS with dropdown. I need to close one while opening the other on click function.

  2. I am also trying to mouseout once the event is out of the dropdown box.

  3. I would like to close the DIV once the click even happens outside the dropdown box.



Following is the HTML

<div class="first-div" style="display:inline-block">
<a class="first-div-link"><h6>REGION</h6></a>
<div class="first-div-dropdown">
<p>Drop down test from first DIV</p>
</div>
</div>

<div id="second-div" style="display:inline-block; float:right">
<a href="#" class="second-div-link"><h6>REGISTER</h6></a>
<div class="second-div-dropdown">
<p>Drop down test from second DIV</p>
</div>
</div>


CSS is following

.first-div-dropdown, .second-div-dropdown{
background-color:#555;
color:white;
height:100px;
width:200px;
}


JS is following

$(document).ready(function(){
$('.first-div-dropdown').hide();
$('.second-div-dropdown').hide();

$('.first-div-link').on('click', function (event){
$('.first-div-dropdown').slideDown(300);
});

$('.second-div-link').on('click', function (event){
$('.second-div-dropdown').slideDown(300);
});

});


Is there any way to use this as a function to control multiple DOMs in the HTML? If so could someone assist me with the current example ?

Thanks

Answer

The path to follow here is use a common class on your items, you don't need to create new classnames if all will have the same styles and will perform the same action. Check this:

$(document).ready(function() {
  $('.cont-div').on('click', 'a', function(e) {
    e.preventDefault();
    $('.div-dropdown').slideUp(300);
    $(this).next('.div-dropdown').stop().slideToggle(300);
  });
  
  //To close if you click outside the container divs
  $('body').on('click', function(e) {
    if (!$(e.target).parents('.cont-div').length) {
      $('.div-dropdown').slideUp(300);
    }
  })
});
body {
  height: 600px;
  background: #e1e1e1;
}
.cont-div {
  display: inline-block;
  vertical-align: top;
  width: 50%;
}
.div-dropdown {
  background-color: #555;
  color: white;
  height: 100px;
  width: 200px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cont-div">
  <a href="#"><h6>REGION</h6></a>
  <div class="div-dropdown">
    <p>Drop down test from first DIV</p>
  </div>
</div><!--
--><div class="cont-div">
  <a href="#"><h6>REGISTER</h6></a>
  <div class="div-dropdown">
    <p>Drop down test from second DIV</p>
  </div>
</div>