druplash
druplash

Reputation: 3

jQuery toggle class issue

There are two buttons which should toggle class for showing or hiding two divs. Only one div should be open at same time. If one div is open and the second button is clicked then the open one should close before the other one opens. Anything i am doing wrong, please can somebody help me?

$('.clicker').click(function() {
    $('.shop_container').find('.wrapper');
    $('.wrapper').toggleClass('show');
    $('.shop_container').find('.wrapper.show').removeClass('show');
});
.wrapper {
  width: 100vw;
  left: -100vw;
  height: 100vh;
  position: fixed !important;
  top: 0px;
  z-index: 99999;
  background: #ff0000;
  transition: all 0.4s ease-in-out;
  overflow-y: scroll;
  overflow-x: hidden;
}

.wrapper.show {
  left: 0px;
  background-color: var(--blue);
  transition: all 0.4s ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="shop_container">
  <div class="clicker">
  First
  </div>
  <div class="clicker">
  Second
  </div>
  <div class="wrapper first">
  Content first
  </div>
  <div class="wrapper second">
  Content second
  </div>
</div>

Upvotes: 0

Views: 36

Answers (1)

Xupitan
Xupitan

Reputation: 1681

Your code :

$('.clicker').click(function() {
    $('.shop_container').find('.wrapper');  // => no action, no effect
    $('.wrapper').toggleClass('show'); // => get all elements whose class is `wrapper` , add class `show` to those elements (both elements are added)
    $('.shop_container').find('.wrapper.show').removeClass('show'); // then remove the `show` class on elements whose class is `show` and `wrapper`
});

As a result, you add the show class to all the div tags that have the class wrapper and then remove them again.

You can use dataset same as :

$('.clicker').click(function() {
  let content = $(this).data('content')
  $('.wrapper.' + content).toggleClass('show').siblings('.wrapper').removeClass('show')
});
.wrapper {
  width: 10vw;
  height: 10vh;
  border: solid 1px #ccc;
  margin: 5px;
  display: none;
}

.wrapper.show {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="shop_container">
  <button class="clicker" data-content='first-content'>
  First
  </button>
  <button class="clicker" data-content='second-content'>
  Second
  </button>
  <div class="wrapper first-content">
    Content first
  </div>
  <div class="wrapper second-content">
    Content second
  </div>
</div>

Upvotes: 1

Related Questions