jeff jeff - 10 months ago 50
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 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>

CSS is following

.first-div-dropdown, .second-div-dropdown{

JS is following


$('.first-div-link').on('click', function (event){

$('.second-div-link').on('click', function (event){


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 ?


Answer Source

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) {
  //To close if you click outside the container divs
  $('body').on('click', function(e) {
    if (!$('.cont-div').length) {
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=""></script>
<div class="cont-div">
  <a href="#"><h6>REGION</h6></a>
  <div class="div-dropdown">
    <p>Drop down test from first DIV</p>
--><div class="cont-div">
  <a href="#"><h6>REGISTER</h6></a>
  <div class="div-dropdown">
    <p>Drop down test from second DIV</p>