Animation in the DOM
Animation is defined as the movement of elements around the screen, and also often includes the manipulation of some other styles, including the spacing between letters & words, and the size of text. Just as with all other examples we have seen so far, you must first locate the element you wish to manipulate. Once again, you may use either the ID or the document tree hierarchy. Then you can use properties such as:
obj.style.top obj.style.left
to move that element around, provided it is absolutely or relatively positioned. Consider the below:
Here's the code for it:
<script type="text/javascript">
function moveitBy(obj, x, y){
obj.style.left=parseInt(obj.style.left)+x+"px"
obj.style.top=parseInt(obj.style.top)+y+"px"
}
function moveitTo(obj, x, y){
obj.style.left=x+"px"
obj.style.top=y+"px"
}
</script>
<div id="hoverimage" style="position: relative; left: 0; top: 0"><img
src="saucer.gif" /></div>
<ul>
<li><a href="javascript:moveitBy(document.getElementById('hoverimage'), 5,
0)">Move by 5px (right)</a></li>
<li><a href="javascript:moveitBy(document.getElementById('hoverimage'), -5,
0)">Move by 5px (left)</a></li>
<li><a href="javascript:moveitTo(document.getElementById('hoverimage'), 0,
-100)">Move to 100px (top)</a></li>
<li><a href="javascript:moveitTo(document.getElementById('hoverimage'), 0,
0)">Move to original position (left)</a></li>
</ul>
Please remember that the top and left positions are not all that can be manipulated in the DOM. Some other noteworthy properties are: letter-spacing, word-spacing, font-family, font-size, color, background, width, height, border, margin, padding, and border-style. The letter-spacing & word-spacing properties are represented in em, font-family is represented by any valid font, font-size defaults to em, color & background take any valid color, width and height default to px, border, margin, and padding take both a color value and a pixel value ("border: blue 3px"), and border-style accepts either solid, dotted, or a null string.
And with that I conclude this tutorial. Have fun learning what's possible using the modern DOM!
- What is the DOM?
- Add elements to the DOM
- Hiding/ showing elements
- Animation in the DOM
This tutorial is written (except for page 1 and conclusion) and contributed by Timothy Francis Brady. Edited by JavaScript Kit. You can visit Timothy's homepage here.