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?

25 of 30 people (83%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can i use mouseOver to play through an array of images then mouseOut to play the opposite way, starting from the last displayed image?
How can I use JavaScript to play a sequence of images?

Apr 3rd, 2000 08:40
Martin Honnen, Justin Stach,


The following sets up some code to solve that problem: it gives you an
  ImageAnimator
constructor function which you call with
  - the name of the IMG element to change
  - an array of img urls to play
  - an optional third speed argument defining the delay between
    imgage swaps in milliseconds


<HTML>
<HEAD>
<SCRIPT>
function ImageAnimator (imgName, imgURLs, spd) {
  this.id = ImageAnimator.cnt;
  ImageAnimator.elements[ImageAnimator.cnt++] = this;
  this.imgName = imgName;
  this.imgURLs = imgURLs;
  this.spd = spd ? spd : 500;
  this.images = new Array(this.imgURLs.length);
  for (var i = 0; i < this.imgURLs.length; i++) {
    this.images[i] = new Image();
    this.images[i].src = this.imgURLs[i];
  }
}
function ImageAnimator_play (up) {
  if (this.tid)
    clearTimeout(this.tid);
  this.up = up || typeof up == 'undefined' ? true : false;
  if (this.up)  
    this.cnt = 0;
  else
    this.cnt--;
  if (!this.image)
    this.image = document[this.imgName];
  if (this.image) {
    if (this.up)
      this.animateUp();
    else 
      this.animateDown();
  }
}
ImageAnimator.prototype.play = ImageAnimator_play;
function ImageAnimator_animateUp () {
  this.image.src = this.images[this.cnt].src;
  this.cnt++;
  if (this.cnt < this.imgURLs.length) {
    this.tid = setTimeout('ImageAnimator.elements[' + this.id 
+ '].animateUp()', this.spd);
  }
  else 
    this.cnt--;
}
ImageAnimator.prototype.animateUp = ImageAnimator_animateUp;
function ImageAnimator_animateDown () {
  this.image.src = this.images[this.cnt].src;
  this.cnt--;
  if (this.cnt >= 0 && this.cnt < this.imgURLs.length) {
    this.tid = setTimeout('ImageAnimator.elements[' + this.id 
+ '].animateDown()', this.spd);
  }
  else 
    this.cnt = 0;
}
ImageAnimator.prototype.animateDown = ImageAnimator_animateDown;
ImageAnimator.cnt = 0;
ImageAnimator.elements = new Array();
</SCRIPT>
<SCRIPT>
var anImageAnimator =
  new ImageAnimator (
    'anImage',
    new Array ('img0.gif',
               'img1.gif', 
               'img2.gif',
               'img3.gif'),
    2000
  );
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript: void 0"
   ONMOUSEOVER="anImageAnimator.play(true)"
   ONMOUSEOUT="anImageAnimator.play(false)"
><IMG NAME="anImage" SRC="img0.gif" BORDER="0"></A>
</BODY>
</HTML>

The code is tested to work with NN4+ and IE4+ though should work with 
NN3 too.