Converting Data Type to Create an Animation Effect

slide down
slide right
slide diagonal
Reset

To create an animation effect, the block element's top and left coordinates must be incremented or decremented gradually from its current position. Unlike the previous example where the top and left values can be reset using number data types, we'll need to first convert the string values IE and NN6+ return for the layer's current top and left coordinates before incrementing and decrementing the values.

This is accomplished simply by invoking the parseInt() method on the top and left property values in order to parse out the number from the string. Storing this converted value in a variable is the most efficient way to work with the newly obtained coordinate. Lets dissect this function:

The sliding functions use the usual id argument, and an argument representing which way the layer will be moved:

**NOTE: this script requires the browser sniffing script from the previous section in order to function properly.
<a href="javascript:slideRight('blockDiv',400)">slide right</a>
function slideRight(id,x) {
var layer = browser(id) // find browser-specific path using browser sniffing function

var currPos = (nn4) ? layer.left : parseInt(layer.style.left) //store layer's current position in variable - get position for IE/NN6 by parsing out the number

   if(currPos < x){ // if currPos is less than 400,
   currPos += 10 currPos equals itself plus 10

      if(nn4){
      layer.left = currPos //set layer position equal to currPos
      }
      else{
      layer.style.left = currPos
      }

   setTimeout("slideRight('" + id + "'," + x+ ")",10) //execute function repeatedly until currPos equals x
   }

}


You may be wondering why we didn't use a for loop to do the incrementing work. Its because the loop executes so fast, the animation effect is lost. So instead, the last line in the function re-invokes itself after a bit of time has passed using the setTimeout() method. See more on calling a function using setTimeout() if you don't understand the use of quotes in this example.

The functions for sliding the layer to the left and diagonally work very similar to the slideRight function.

View the Source



Home | Contact