[thelist] Very basic JavaScript question

John.Brooking at sappi.com John.Brooking at sappi.com
Thu Sep 30 08:24:34 CDT 2004

Shane Miller said:
>...  What I'd like to do, though, is "reset" back to the 
>first picture when I've reached the last image in the array. 
>I would like to hard code that, with an additional if-then 
>statement that if the index is four then change the index to 
>zero, but I don't know the syntax.


   function next() {
      if (document.images) {
         start = ( start + 1 ) % index;
         document.images['imageName'].src = arrayOfImages[start];

The % operator is modulus, which gives you the remainder of dividing the
first operand by the second. It is very handy for just this situation. If
you do the math for each value of start (given your index value of 5),
you'll find that when start is 0 through 3, the expression "( start + 1 ) %
index" yields the same thing as start + 1 (the division yields 0 with the
remainder being the divisor itself). However, significantly, when start is
4, adding one gives you 5, and dividing 5 by 5 gives you 1 with 0 remainder,
so start ends up back at 0, just as you want. In general, for any value of
index, this expression cycles between 0 and index - 1.

- John

This message may contain information which is private, privileged or
confidential and is intended solely for the use of the individual or entity
named in the message. If you are not the intended recipient of this message,
please notify the sender thereof and destroy / delete the message. Neither
the sender nor Sappi Limited (including its subsidiaries and associated
companies) shall incur any liability resulting directly or indirectly from
accessing any of the attached files which may contain a virus or the like. 

More information about the thelist mailing list