$(".animate").click(function() { var $this = $(this); var $animLeft = $this.hasClass("left"); var $animRight = $this.hasClass("right"); if ($animLeft) { $(this).animate({ "left": "-=50px" }, "slow"); } else if ($animRight) { $(this).animate({ "left": "+=50px" }, "slow"); } }); $(".undo").click(function(t) { t.preventDefault(); $(this); $(".example-animates").find(".fa").css("left", 0); });
<div class="container"> <h2>Animate Images/Icons in JavaScript using jQuery animate function - The Class 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 animate left"></i></div> <div class="d-flex justify-content-center"><i class="fa fa-arrow-right fa-3x animate right"></i></div> </section> </div>
.example-animates { overflow: hidden; margin-bottom: 1rem; } .example-animates i { position: relative; cursor: pointer; }