faqts : Computers : Programming : Languages : JavaScript : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

39 of 75 people (52%) answered Yes
Recently 10 of 10 people (100%) answered Yes


How can I move an image with javascript for simple animation?

May 12th, 2001 16:52
Colin Fraser, Paul Buck,

I hope this is what you are looking for: 
<title>Simple animated layers>/title>
<script language="javascript"><!--
function moveLayer1()
if (window.document.layer1.left !=175)
window.document.layer1.moveTo(175,25) //jump to new position
window.document.layer1.moveTo(25,25);  //return to open position
function moveLayer2()
var x = window.document.layer2.left
if (window.document.layer2.left !=175) {
   	for (i=0; i<15;i++) {
	    x = x+10
	    //set up the variable value
	    window.document.layer2.moveTo(x,150) ;
	    for (j=0;j<250;j++) ;  //uses CPU time setting scroll rate.
else {
   	for (i=0; i<15;i++) {
	    x = x-10
	    //return the div to its starting point
	    window.document.layer2.moveTo(x,150) ;
	    for (j=0;j<250;j++) ;  //uses CPU time setting scroll rate.
          window.document.layer2.moveTo(25,150); }
<div id="layer1" style="position:absolute; height:100px; width:100px;
z-index:1; left:25px; top:25px; background:red">
<a href="javascript: void" onClick="moveLayer2(); return
<div id="layer2" style="position:absolute; height:100px; width:100px;
z-index:2; left:25px; top:150px; background:yellow">
<a href="javascript: void" onClick="moveLayer1(); return
rest of page here
There are a couple of things here, animating turned out to be a lot 
easier than I thought, but setting the divs up to suit both browsers was 
not simple. I tried to use a timeOut() but it failed miserably and I 
dont know why. I had it working in IEv5.5 and nn, but I am not overly 
happy with the IE, sometimes it worked sometimes it didn't and I just 
ran out of patience with IE. Placing images inside the layers does not 
cause any problems, and if you want to make the divs run up and odwn the 
page, just change the top param to a variable. Good luck.