I've used jQuery for a long time, and now I'm going to do some animations with vanilla JS. Here's my code so far:
var box = document.getElementById('box'),
a1end,
a2end,
cdend,
a3end,
a4end,
animate1 = setInterval(function() {
if (box.style.top === (window.innerHeight - 120) + 'px') {
clearInterval(animate1);
a1end = true;
}
box.style.top = (
+box.style.top.replace('px', '') + 1
) + 'px';
}, 1),
animate2 = setInterval(function() {
if (box.style.left === (window.innerWidth - 120) + 'px') {
clearInterval(animate2);
a2end = true;
}
box.style.left = (
+box.style.left.replace('px', '') + 1
) + 'px';
}, 1);
checkEnd1(function() {
box.style.background = 'greenyellow';
box.innerText = 'Next stage starts in 5 seconds';
var i = 4,
cd = setInterval(function() {
if (!i) {
clearInterval(cd);
cdend = true;
}
box.innerText = 'Next stage starts in ' + i + ' seconds';
i--;
}, 1000);
});
checkEnd2(function() {
box.style.background = 'white';
box.innerText = '';
var animate3 = setInterval(function() {
if (box.style.left === '20px') {
clearInterval(animate3);
a3end = true;
}
box.style.left = (
+box.style.left.replace('px', '') - 1
) + 'px';
}, 1);
});
checkEnd3(function() {
var animate4 = setInterval(function() {
if (box.style.top === '20px') {
clearInterval(animate4);
a4end = true;
}
box.style.top = (
+box.style.top.replace('px', '') - 1
) + 'px';
}, 1);
});
checkEnd4(function() {
box.style.background = 'lightcyan';
box.innerText = 'Animation complete';
});
function checkEnd1(fn) {
(a1end && a2end) ? fn() : setTimeout(function() {
checkEnd1(fn);
}, 200);
}
function checkEnd2(fn) {
(cdend) ? fn() : setTimeout(function() {
checkEnd2(fn);
}, 200);
}
function checkEnd3(fn) {
(a3end) ? fn() : setTimeout(function() {
checkEnd3(fn);
}, 200);
}
function checkEnd4(fn) {
(a4end) ? fn() : setTimeout(function() {
checkEnd4(fn);
}, 200);
}
I've also noticed that the first animation isn't working as excepted. Out of curiousity, I tried it with jQuery's .animate()
and it worked as excepted:
$('#box').animate({
top: window.innerHeight - 120,
left: window.innerWidth - 120
});
Note: please don't tell me to use jQuery or other libs, I want to use vanilla.
Bounty Edit
Currently, the animation goes diagonally for a while, then when it reaches the bottom, it continues to go sideways. If you tell me how to make it go diagonally all the time, I'll give you a bounty.