Current course:

Movement with Javascript & CSS


With CSS, we can edit the location of something using positioning.

For example, if an image or div absolutely positioned on the left side of the screen, and we want it to be further right, we could increase it's "left" CSS attribute, and it would go further to the right.

But if we wanted it to animate, we'd have to have it increase over a period of time - but CSS doesn't have the capability to run over a period of time - it just gets run when the page loads up, then it's done. If only we could use Javascript to change it's CSS!

We're in luck! Javascript DOES let us change CSS - AND, as you've learned, we can have Javascript run every X number of miliseconds with Javascripts interval function.


      <script type="text/javscript">
            var myInterval;
            function moveRight(elemId, rightPos) {
                  if(!myInterval) { myInterval = setInterval("moveRight('"+elemId+"', 605)", 25); }
                  var e = document.getElementById(elemId);
                  currentLeft = parseInt(;
                  if(currentLeft < rightPos) {
               = (currentLeft + 10) + "px";
                  } else {

<div style="position:relative; border:2px solid #555; background-color:#CCC; margin:20px 0px; height:100px; width:700px;">
      <div id="myDiv" onclick="moveRight('myDiv', 500);" style="position:absolute; cursor:pointer; left:12px; top:12px; width:75px; height:75px; border:1px solid #300; background-color:#900;"></div>
</div><br />


Other thoughts/ideas

You could make another function to move it to the left - so once it hit the right side, you could stop the moveRight interval, and start one for moveLeft - this would create a bouncing effect.

You don't have to move it by the same distance each time - to make it slide into place, try moving it half the distance that it has left to go - for example if it were going to move 100px - the first move would move it 50px, the second, 25px, the third 12.5px, the fourth 6.25px...etc. This creates the effect of slowing down as it slides into place. (REMINDER: You shouldn't have to hard-code each move - you could instead, just calculate the new distance each time).