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?
JavaScript
x
18
18
1
$(".box").on('click tap', function() {
2
if($(this).hasClass('active')){
3
$(this).animate({
4
marginLeft: "-=150px",
5
}, 500, function() {
6
$(this).removeClass('active');
7
});
8
}else{
9
$(this).animate({
10
marginLeft: "+=150px",
11
}, 500, function() {
12
$(this).addClass('active');
13
});
14
}
15
});
16
17
18
// $(this).toggleClass("active", 1000, "easeInOutQuad");
JavaScript
1
9
1
.box{
2
width: 100px;
3
height: 100px;
4
background-color: red;
5
}
6
7
.active{
8
margin-left: 150px;
9
}
JavaScript
1
2
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<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:
JavaScript
1
3
1
$(".box").on('click tap', function() {
2
$(this).toggleClass('active');
3
});
JavaScript
1
10
10
1
.box {
2
width: 100px;
3
height: 100px;
4
background-color: red;
5
transition: margin-left 0.5s; /* <== */
6
}
7
8
.active {
9
margin-left: 150px;
10
}
JavaScript
1
3
1
<div class="box"> BOX </div>
2
3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>