skip to Main Content

I have a function that moves buttons by adding css to the button using JQuery. My code looks like this

function btnToggle() {
  $('.btnClass').addClass('active');
  if ($('.btnClass').hasClass('active')) {
    $('.btnClass').css('margin-right', '250px');
  } else {
    $('.btnClass').removeClass('active');
  }
}
.btnClass {
  background: aqua;
  position: absolute;
  right: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btnClass">button 1</button>

<button onclick="btnToggle()">slide</button>

But removeClass doesn’t work and the button can’t go back to its original position

2

Answers


  1. You’re adding the class unconditionally, so the if condition will always be true.

    Instead of setting the style in the JavaScript, do that in the CSS. Then use toggleClass().

    function btnToggle() {
      $('.btnClass').toggleClass('active');
    }
    .btnClass {
      background: aqua;
      position: absolute;
      right: 2em;
    }
    
    .btnClass.active {
      margin-right: 250px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button class="btnClass">button 1</button>
    
    <button onclick="btnToggle()">slide</button>
    Login or Signup to reply.
  2. function btnToggle() {
      if ($('.btnClass').hasClass('active')) {
        $('.btnClass').removeClass('active');
      } else {
        $('.btnClass').addClass('active');
      }
    }
    .btnClass {
      background: aqua;
      position: absolute;
      right: 2em;
    }
    
    .active {
      margin-right: 250px
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button class="btnClass">button 1</button>
    
    <button onclick="btnToggle()">slide</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search