Home > front end >  JQuery - removeClass inactive
JQuery - removeClass inactive

Time:12-27

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 >button 1</button>

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

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

CodePudding user response:

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 >button 1</button>

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

CodePudding user response:

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 >button 1</button>

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

  • Related