Animate Images/Icons in JavaScript using jQuery animate function - The Data- method
Using jQuery Animate function to animate icons when clicked. Using Data- (s) as the target element(s).
HTML
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="container">
<h2>Animate Images/Icons in JavaScript using jQuery animate function - The Data- method<small><small><a class="btn btn-link btn-sm undo" role="button" href="#"><i class="fa fa-undo"></i></a></small></small>
</h2>
<small>Click on arrow icons to animate. Click the reset icon to reset icons.</small>
<section class="example-animates">
<div class="d-flex justify-content-center"><i class="fa fa-arrow-left fa-3x" data-animate="left"></i></div>
<div class="d-flex justify-content-center"><i class="fa fa-arrow-right fa-3x" data-animate="right"></i></div>
</section>
</div>
CSS
.example-animates {
overflow: hidden;
margin-bottom: 1rem;
}
.example-animates i {
position: relative;
cursor: pointer;
}
JavaScript
$("[data-animate]").click(function() {
var $this = $(this);
var $animDir = $this.data("animate");
if ($animDir == "left") {
$(this).animate({
"left": "-=50px"
}, "slow");
} else if ($animDir == "right") {
$(this).animate({
"left": "+=50px"
}, "slow");
}
});
$(".undo").click(function(t) {
t.preventDefault();
$(this);
$(".example-animates").find(".fa").css("left", 0);
});