Home > Enterprise >  How to make my button only show the div on its group when I click it
How to make my button only show the div on its group when I click it

Time:02-11

Currently when I click the 1st button both hidden divs are showing. My goal is when I click the 1st button it only shows the hidden div on its group. And if I click the 2nd button it only shows the hidden div on its group.

Can anyone help me with how to achieve it?

$(document).ready(function () {
    $(".btn").on("click", function () {
        $(".hidden").addClass("active");
    });
    
    $(".closed").on("click", function (){
        $(".hidden").removeClass("active")
    })
})
.btn {
  background: blue;
  color: #ffffff;
  font-weight: 600;
  padding: 20px;
}


.hidden {
  width: 100px;
  height: 100px;
  background: yellow;
  display: none;
}


.hidden.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
      <div >Show</div>
      <div >
        <div >Click to hide</div>
      </div>
  </div>
</div>

<br>

<div >
  <div >
      <div >Show</div>
      <div >
        <div >Click to hide</div>
      </div>
  </div>
</div>

CodePudding user response:

Your code

$(".hidden").addClass("active");

selects all .hidden elements (hence your issue).

Within the click event you need to use this to refer to the element being clicked and then use relative DOM navigation to find the element you do want.

In your case it's the next sibling, so .next() will suffice for show, but hide/close will need to find its parent .hidden

$(document).ready(function () {
    $(".show").on("click", function () {
        $(this).next().addClass("active");
    });
    
    $(".close").on("click", function (){
        $(this).closest(".hidden").removeClass("active")
    })
})
.show {
  background: blue;
  color: #ffffff;
  font-weight: 600;
  padding: 20px;
}


.hidden {
  width: 100px;
  height: 100px;
  background: yellow;
  display: none;
}


.hidden.active {
  display: block;
}

.close { background-color:#ccc; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
      <div >Show</div>
      <div >
        <div >Click to hide</div>
      </div>
  </div>
</div>

<br>

<div >
  <div >
      <div >Show</div>
      <div >
        <div >Click to hide</div>
      </div>
  </div>
</div>

  • Related