animated div

by dogmeethorse

HTML

<div id='sample'>hello</div>
<div id ='counter'></div>

CSS

div{
    background-color:red;
    height:50px;
    width:50px;
}
#counter{
    margin-left:150px;
}

JavaScript

var d = document.getElementById('sample');
var cDiv = document.getElementById('counter');
var counter = 0;
var margin = 0;
var increment = 1;
function updateLocation(){
    counter++;
    if(Math.floor(counter / 100) % 2 == 0){ 
        margin += increment;
    }
    else{
        margin -= increment;       
    }
    d.style.marginLeft = margin + "px";
    cDiv.innerHTML = counter;
    cDiv.style.marginLeft =  150 - margin + "px";
    if(counter >1000){
        counter = 0;
    }
}
var myInterval = setInterval( updateLocation, 10);