skip to Main Content

I have a problem. Two buttons with class .sert_btn should toggle classes of images. The left button works in a right way, but the rigth one doesn’t. HELP PLS

class passive – display: none;

I tried another constructions for $(document), as $(‘.sertbtn) and $(‘#btn_r’), but result is the same

let i = 0;
$(document).on('click', '.sert_btn', function() {
  i++;
  if (i % 2 == 0) {
    $('#s_1').addClass('passive');
    $('#s_2').removeClass('passive');

  } else {
    $('#s_2').addClass('passive');
    $('#s_1').removeClass('passive');
  }
});
.passive { display: none }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<div class="docs docs_dt">
  <button class="sert_btn">Click</button>
  <img id="s_1" class="sert_img" src="https://pngfre.com/wp-content/uploads/Turtle-1-300x187.png">
  <img id="s_2" class="sert_img" src="https://pngfre.com/wp-content/uploads/Penguin-png-1-155x300.png">
  <button id="btn_r" class="sert_btn">Click</button>
</div>

2

Answers


  1. This is simpler and makes more sense

    $(document).on('click', '.sert_btn', function() {
      // show left image when left is clicked, show right when right is clicked
      //$('#s_1').toggleClass('passive', this.id === "btn_l");
      //$('#s_2').toggleClass('passive', this.id === "btn_r");
      // toggle whenever either button is clicked
      $('#s_1').toggleClass('passive');
      $('#s_2').toggleClass('passive');
    });
    .passive {
      display: none
    }
    img { height:50px; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
    <div class="docs docs_dt">
      <button id="btn_l" class="sert_btn">Click</button>
      <img id="s_1" class="sert_img passive" src="https://pngfre.com/wp-content/uploads/red-arrow-27-1-1024x1024.png">
      <img id="s_2" class="sert_img" src="https://pngfre.com/wp-content/uploads/red-arrow-26-1-1024x1024.png">
      <button id="btn_r" class="sert_btn">Click</button>
    </div>
    Login or Signup to reply.
  2. This code should toggle the class on the images each time you click either of the two buttons.

    $('.sert_btn').click(function() {
      const hasPassive = $('#s_1').hasClass('passive');
      $('#s_1').toggleClass('passive', !hasPassive);
      $('#s_2').toggleClass('passive', hasPassive);
    });
    .passive { display: none }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="docs docs_dt">
      <button class="sert_btn">Click</button>
      <img id="s_1" class="sert_img passive" src="https://static-cdn.jtvnw.net/ttv-boxart/509658-188x250.jpg">
      <img id="s_2" class="sert_img" src="https://static-cdn.jtvnw.net/ttv-boxart/516575-188x250.jpg">
      <button id="btn_r" class="sert_btn">Click</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search