JS Animation Test
Changing position values with JS to make simple animations
HTML
<div id="box"></div>
CSS
#box {
background-color: blue;
width: 20px;
height: 20px;
position: absolute;
}
JavaScript
// Assign div element to var `box`
box = document.getElementById("box");
// Center `box`.
box.style.left = ((window.innerWidth / 2) - 10) + "px";
box.style.top = ((window.innerHeight / 2) - 10) + "px";
box.style.right = ((window.innerWidth / 2) + 10) + "px";
box.style.bottom = ((window.innerHeight / 2) + 10) + "px";
// Initialize move increments.
ver = 2;
hor = 3;
// Make it move!
t = setInterval(function () {
if (parseInt(box.style.top.substr(0,box.style.top.length-2),10) <= 0 || parseInt(box.style.bottom.substr(0,box.style.bottom.length-2),10) <= 20) {
ver = -ver;
} else if(parseInt(box.style.left.substr(0,box.style.left.length-2),10) <= 0 || parseInt(box.style.right.substr(0,box.style.right.length-2),10) <= 20) {
hor = -hor;
}
box.style.top = parseInt(box.style.top.substring(0,box.style.top.length-2),10) + ver + "px";
box.style.left = parseInt(box.style.left.substring(0,box.style.left.length-2),10) + hor + "px";
box.style.bottom = parseInt(box.style.bottom.substring(0,box.style.bottom.length-2),10) - ver + "px";
box.style.right = parseInt(box.style.right.substring(0,box.style.right.length-2),10) - hor + "px";
}, 1);