Fly-in / fly-out animation with custom easing.

Online preview: /my/demo/fly.html

<!DOCTYPE html>
<body>
<div id="gift-fly" style=" position: absolute; width: 50px;height: 50px;background-color: #327dff "> Animation Box</div>
</body>
<script>
let flyDiv = document.getElementById("gift-fly")
animate(flyDiv, {"left": 500}, 3000, "easeIn").then(res => {
console.log("fly in done")
animate(flyDiv, {"left": 0}, 3000, "easeOut").then(res => {
console.log("fly out done")
})
})

/**
* @param elem {HTMLElement} element to animate
* @param params {JSON} properties to change
* @param duration {Number} ms duration
* @param easing {String} easing type: easeIn / easeOut
*/
function animate(elem, params, duration, easing) {
return new Promise(success => {
let tween = {
easeIn: function (t, b, c, d) { return c * (t /= d) * t + b; },
easeOut: function (t, b, c, d) { return -c * (t /= d) * (t - 2) + b; }
};
let attribute = {
get: function (elem, attr) {
let val;
if (elem.currentStyle) {
if (attr === "opacity") val = elem.filters.alpha[attr]; else val = elem.currentStyle[attr];
} else {
val = getComputedStyle(elem)[attr];
if (attr === "opacity") val = 100 * val;
}
return val;
},
set: function (elem, attr, val) {
if (attr == 'opacity') {
elem.style.filter = 'alpha(opacity=' + (val) + ')';
elem.style.opacity = (val) / 100;
} else {
elem.style[attr] = val + 'px';
}
}
};
let effect = {
animate: function (elem, params, duration, easing) {
let dt = new Date().getTime(), b = 0, c = 0, d = duration || 500, fps = 1000 / 60;
let changes = [];
for (let attr in params) {
b = parseFloat(attribute.get(elem, attr));
c = params[attr] - b;
changes.push({ attr, b, c });
}
easing = easing || "easeOut";
setTimeout(function step() {
let t = new Date().getTime() - dt;
for (let i = 0; i < changes.length; i++) {
let { b, c, attr } = changes[i];
attribute.set(elem, attr, tween[easing](t, b, c, d));
if (d <= t) {
attribute.set(elem, attr, params[attr]);
success();
return;
}
}
setTimeout(step, fps);
}, fps);
}
};
effect.animate(elem, params, duration, easing);
})
}
</script>
</html>