Here is a fiddle using animate
. I've added some code comments to walk you through what's going on.
HTML:
<h1 class="test">test</h1>
JavaScript:
//Get the element you want to animate
var testElement = $('.test');
function run(v){
//Reverse the array
var reversed = JSON.parse(JSON.stringify(v)).reverse();
$(v[0]).animate(v[1], {
//The speed the element moves - lower is faster
duration: 500,
step: function(val) {
//Adding the transform to your element
testElement.css("transform", `translateX(${val}px)`);
},
done: function(){
//Re-running the function but in reverse with the reverse we did above
run(reversed)
}
})
};
//Calling our function and passing in the parameters
run([{y:0}, {y:100}])
You'll need to play around with the values you pass into run()
.
There is a similar answer here that show's how this is done with translateY
, however I found the code a bit hard to grasp at first glance so I've dissected it a bit and made it work for your scenario with translateX
.