Home > Software design >  jQuery toggles all elements
jQuery toggles all elements

Time:10-01

I want to expand a submenu when a button/icon is clicked. The icon should be animated. unfortunately I couldn't figure out how to toggle only the clicked buttons class.

$(".secondLayer").click(function() {
  $(".plus-button").toggleClass("open");
});
.accordion_header {
  position: relative;
  width: 500px;
  background-color: #eee;
  height: 50px;
  padding: 10px;
}

.accordion_header h2 {
  display: inline-block;
  vertical-align: middle;
}

.plus-button {
  height: 100%;
  margin-top: 13px;
  margin-right: 20px;
  margin-left: 7px;
  position: relative;
  display: inline-block;
  padding: 0px 0px;
  transition: .3s;
  cursor: pointer;
  float: left;
}

.plus-button:hover {
  opacity: 0.75;
}

.plus-icon {
  display: inline-block;
  width: 20px;
  height: 3px;
  background-color: #0a4e9b;
  background-repeat: no-repeat;
  background-size: 1.5em 1.5em;
  user-select: none;
  border-radius: 0.75em;
  color: green;
  transition: .3s;
  position: relative;
}

.plus-icon:before {
  display: inline-block;
  width: 20px;
  height: 3px;
  background-repeat: no-repeat;
  background-size: 3px 3px;
  user-select: none;
  border-radius: 0.75em;
  transition: .3s;
  position: absolute;
  content: '';
  transform-origin: 10px center;
  transform: rotate3d(0, 0, 1, 90deg);
  color: red;
  background-color: #0a4e9b;
}

.open.plus-button .plus-icon:before,
.open.plus-button {
  top: 0;
  width: 20px;
  transform: rotate3d(0, 0, 0, 90deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="secondLayer">
  <div class="plus-button">
    <div class="plus-icon"></div>
  </div>
</div>
<div class="secondLayer">
  <div class="plus-button">
    <div class="plus-icon"></div>
  </div>
</div>

CodePudding user response:

So select the button inside of the element. Click has a reference to the element. Use that and find the button in it.

$(".secondLayer").click(function () {
    $(this).find(".plus-button").toggleClass("open");
});
  • Related