Skip to content
Advertisement

Looking for an efficient way to animate toggle class

I have a CSS class that has left-margin: 150px and I just want to function it in an animated way. ToggleClass in jQuery works but without any animation. $(this).toggleClass("active", 1000, "easeInOutQuad");

I managed to do it animated using addClass and removeClass. But I am wondering if there is any easier way to do it. it takes 10 lines of code while there should be something much more efficient.

Any ideas?

$(".box").on('click tap', function() {
if($(this).hasClass('active')){
      $(this).animate({
        marginLeft: "-=150px",
      }, 500, function() {
        $(this).removeClass('active');
      });    
}else{
      $(this).animate({
        marginLeft: "+=150px",
      }, 500, function() {
        $(this).addClass('active');
      });    
}
});


// $(this).toggleClass("active", 1000, "easeInOutQuad");
.box{
width: 100px;
height: 100px;
background-color: red;
}

.active{
margin-left: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"> BOX </div>

Advertisement

Answer

I’d use CSS transition to do it. Add transition: margin-left 0.5s; (or similar) to your .box style rules:

$(".box").on('click tap', function() {
    $(this).toggleClass('active');
});
.box {
    width: 100px;
    height: 100px;
    background-color: red;
    transition: margin-left 0.5s; /* <== */
}

.active {
    margin-left: 150px;
}
<div class="box"> BOX </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement