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
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()
.