Week 08: Lecture – Animation


CSS properties can be accessed through the DOM through the style attribute of any element. However, the DOM tree only lists styles set within style tags or set by JavaScript dynamically. It does not pull in styles from external scripts or css embeded in style tags.

 // element.style.property
 var item = document.getElementById('item');
 var itemHeight = item.style.height;
 // set the height (don't forget the 'px')
 item.style.height = '20px';

Some styles use the dash (-) in their names. When accessed in JavaScript, we cannot use those names exactly–since that would imply a subtraction of two variables. So in JavaScript, we remove the dash and capitalize the next Letter (to make it lowerCamelCase):

 // element.style.propertyName
 var item = document.getElementById('item');
 var itemFont = item.style.fontFamily; // font-family
 var itemIndex = item.style.zIndex; // z-index
 var itemBgColor = item.style.backgroundColor; // background-color


Animation is done in JavaScript using a DOM styling and is usually managed with either the setTimeOut method or the setInterval method:

setTimeout(function, milliseconds)

This method allows you to call a function after a specific delay.

       var i = 1;
       // alert after 2 seconds
       // functions here work like eval()
       var delayAction = setTimeout("alert(" + i + ")", 2000); 
       var myFunc = function() {
       // alert after .5 seconds
       var anotherAction = setTimeout(myFunc, 500);


This method allows you to cancel or clear an action.

       clearTimeout(delayAction); // cancel the delayAction

setInterval() and setTimeout()

Both setInterval() and setTimeout() require two arguments.

  • Function – the function that will run when executed
  • Time – time in milliseconds
// run myfunc after 300 milliseconds (1/1000 seconds) has elapsed
setTimeout(myfunc, 300);
// run myfunc contiuously every 500 milliseconds
setInterval(myfunc, 500);

Both setTimeout() and setInterval() can be called in one of the the following manner:

// As a String
setTimeout("myFunction()", 1000);
// As a reference to the function held in a variable
setTimeout(myFunction, 1000);
// As an Anonymous function
	// run code here
}, 1000);

clearTimeout() and clearInterval()

You can clear Timeouts and Intervals in the following manner:

	var myTimeout = setTimeout(myFunction, 1000);

Notice that a reference to the Timeout or Interval must be set in order to use clearTimeout() and clearInterval()

For more on setTimeout() and setInterval() visit: http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Web Development Courses, Rants, Tutorials and Hacks