Home > other >  jQuery toggle class issue
jQuery toggle class issue

Time:06-25

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 >
  <div >
  First
  </div>
  <div >
  Second
  </div>
  <div >
  Content first
  </div>
  <div >
  Content second
  </div>
</div>

CodePudding user response:

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 >
  <button  data-content='first-content'>
  First
  </button>
  <button  data-content='second-content'>
  Second
  </button>
  <div >
    Content first
  </div>
  <div >
    Content second
  </div>
</div>

  • Related