ptg 12.5 Introduction to Slideshows 441 12.5 Introduction to Slideshows JavaScript slide shows are great for creating photo albums, auction listings, digital pre- sentations, art galleries, 3D carousels, and so on (see Figure 12.20). Once you get a basic slide show working, you can reuse the code to create other slide shows and change the images accordingly. There are numerous sites on the Web where you can get excellent JavaScript slideshow libraries that have already been created and free for reuse. The examples provided in this text are to give you some insight on how a simple JavaScript Figure 12.19 After clicking on the image, this alert box displays the window’s dimensions. Figure 12.20 A carousel slideshow (http://www.dynamicdrive.com/dynamicindex14/carousel.htm). From the Library of WoweBook.Com ptg 442 Chapter 12 • Working with Images (and Links) slideshow is created, how to control the start and stop of the slideshow, how to create clickable images, and simple animation. Once you understand the basics, understanding and debugging existing code will be much easier. When you build a slide show, the visitor of your site must be a first consideration; for example, what is the bandwidth and type of browser, or will the load time be too slow if you are loading a large number of images? Navigation is another important consider- ation. Will the visitor be able to control the slideshow manually or will it automatically start when the page loads and stop when it exits or when it has completed a specified number of cycles? You might want to create buttons to control the slideshow such as start, pause, go back, forward, speed up, slow down, stop, and so on. You might want to create optional hyperlinks or clickable images where each frame leads to a different URL. You might want to randomly display the images or show them in a certain sequence. The size of the images also weighs into a well-constructed slideshow. When you have a series of images coming from different sources, they will probably not have the same height and width. When the slideshow starts, images of different sizes will give the page a jumpy appearance. You might want to crop the images to make them all the same size. Because the first image you load will be followed or overlaid by the next series of images, the dimensions of that image will determine the size of the rest of the images giving the page a smooth transition as each one loads. However, if you have images of varying dimensions, forcing all the images to be of the same size, might distort the image objects if not proportionally scaled. You might also want to get a sleek fade-in effect when one image replaces the previous image, or get persistence so that when the user reloads the page, he or she picks up in the slideshow where it left off. Figure 12.21 on page 443, called “Ultimate Fade-in slideshow (v2.1) located at dynam- icdrive.com, demonstrates a sophisticated, cross-browser, fade-in slideshow script, and the site offers free code to build your own slideshow similar to the demos shown later, saving lots of time and energy. Before downloading sophisticated scripts from the Web, this chapter describes a very basic slideshow to help you understand how JavaScript slideshows work, which will help you later when you are debugging, updating, revising, and maintaining more complicated scripts. Note: To disable the viewer from right-clicking the mouse to get a menu for saving images from your page, go to http://www.dynamicdrive.com/dynamicindex9/noright2.htm for free Java- Script code. 12.5.1 A Simple Slideshow with Controls Example 12.10 is a JavaScript program that cycles through a selection of images. It makes use of image replacement, a timer function, and buttons that serve as controls to give the user the ability to start and stop the slideshow. See Chapter 13 for an example (Example 13.11) of a slideshow using a mouse rollover. From the Library of WoweBook.Com ptg 12.5 Introduction to Slideshows 443 Figure 12.21 http://www.dynamicdrive.com/dynamicindex14/fadeinslideshow.htm (see page 442). EXAMPLE 12.10 <html> <head><title>Slide Show</title> <script type="text/javascript"> var i=0; var timeout; 1 function preLoadImages(){ if(document.images){ 2 planet = new Array(); // global variable 3 planet[0]=new Image(); planet[0]="/images/Venus.jpg"; planet[1]=new Image(); planet[1]="/images/Neptune.jpg"; planet[2]=new Image(); planet[2]="/images/Earth.jpg"; planet[3]=new Image(); planet[3]="/images/Mars.jpg"; Continues From the Library of WoweBook.Com ptg 444 Chapter 12 • Working with Images (and Links) planet[4]=new Image(); planet[4]="/images/Jupiter.jpg"; } else{ alert("There are no images to preload"); } } 4 function startSlideShow(){ 5 if(i < planet.length){ 6 document.images["planet_pic"].src = planet[i]; i++; } else{ i=0; 7 document.images["planet_pic"].src = planet[i]; } 8 timeout = setTimeout('startSlideShow()',1500); } 9 function stopSlideShow(){ clearTimeout(timeout); } </script> </head> <body bgColor="black" onload = "preLoadImages()"> 10 <img name="planet_pic" src="Jupiter.bmp" height="348" width="545px" /> <form> <br /><br /> <input type=button value="Start Show" onClick="return startSlideShow();"/> <input type=button value="Stop Show" onClick="return stopSlideShow();"/> </form> </body> </html> EXPLANATION 1 A function called preLoadImages() is defined in the head of the document. It will define a list of images that will be loaded before anything else. 2 A new array called, planets, will is declared. It will be assigned the images of the planets. 3 The Image() constructor creates and preloads a new image object called planet[0]. 4 The function called startSlideShow() allows the user to determine when to start the slideshow. 5 The variable i is initially set to 0 and is used as an index in the array called planets. As long as the index value is less than the size of the array, the statements in the if condition will be executed. EXAMPLE 12.10 (CONTINUED) From the Library of WoweBook.Com ptg 12.5 Introduction to Slideshows 445 12.5.2 A Clickable Image Slideshow In Example 12.11 a set of planet images is displayed as a slideshow. If the viewer clicks one of the planets, he or she is redirected to a Web page that describes that planet. This 6 The src property of the image object is assigned a new picture. By using the name of the image as an index value of the images array, JavaScript can determine which image object to use. (Another way to get to the image: document.planet_pic.src or document.images[0].src.) 7 Once the index value exceeds the length of the array, the index value, i, is reset to 0 and the slideshow begins again. 8 The timer is set so that once every 1.5 seconds a new picture is displayed. 9 When the user clicks the button labeled “Stop Show,” the clearTimeout() function is called, causing the timer to stop. The argument, timeout, is a reference to the timer set on line 8. 10 The initial image is a picture of the planet Jupiter (see Figure 12.22). It is given size dimensions, which will determine the size of all images in the slideshow. If the images are of different dimensions, they will have to be scaled to this size. Not properly sizing images will give them a distorted appearance. Figure 12.22 Planet slideshow with two control buttons. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 446 Chapter 12 • Working with Images (and Links) is accomplished by assigning the image to a link; that is, a link that is assigned a Java- Script user-defined function and triggered when the user clicks the image. EXAMPLE 12.11 </html> <head><title>Planet Slide Show</title> <script type="text/javascript"> 1 var timeout; var step=0 var whichimage=0; 2 var planet=new Array(); function preLoadImages(){ 3 planet[0]=new Image(); planet[0]="/images/Jupiter.bmp"; planet[1]=new Image(); planet[1]="/images/Neptune.bmp"; planet[2]=new Image(); planet[2]="/images/Earth.jpg"; planet[3]=new Image(); planet[3]="/images/venus.jpg"; planet[4]=new Image(); planet[4]="/images/http:/mars.jpg"; } 4 function slideShow(){ 5 document.images["planet_pic"].src=planet[step]; 6 whichimage=step; 7 if (step < planet.length){ step++; } else{ 8 step=0; } 9 setTimeout("slideShow()",1800); } 10 function slideLink(){ 11 switch(whichimage){ case 0: 12 window.location= "http://www.nasa.gov/worldbook/jupiter_worldbook.html"; break; case 1: window.location= "http://www.aerospaceguide.net/planet/planetneptune.html" break; case 2: window.location= "http://www.windows.ucar.edu/tour/link=/earth/earth.html"; break; From the Library of WoweBook.Com ptg 12.5 Introduction to Slideshows 447 case 3: window.location= "http://csep10.phys.utk.edu/astr161/lect/venus/venus.html"; break; case 4: window.location= "http://www.nasa.gov/worldbook/mars_worldbook.html"; break; } } </script> </head> 13 <body bgColor="black" onLoad = "preLoadImages(); slideShow()"> <font color="white"> <big> Click on a Planet<br /><br /> 14 <a href="JavaScript:slideLink()"> <img src="Jupiter.bmp" name="planet_pic" border="0" width="120" /></a> </big> </font> </body> </html> EXPLANATION 1 Global variables that will be used by the functions in this program are declared in the head of the document. 2 The Array() constructor creates an array object, called planets. 3 The Image() constructor will preload and cache four images and assign them to the array created in line 2. 4 This function starts the slideshow. It displays an array of images one at a time at selected intervals of 1.8 seconds. 5 The src property of the first element of the image array is assigned an image called Jupiter.bmp. Each array element is assigned a different image. Every 1.8 seconds an image is replaced with a new image in the array, until all the planets have been displayed, at which time the index value, called step, is set back to 0. 6 The variable, whichimage, is used to get the index value of the image that was just clicked by the user. This value will be used in the switch statement on line 11. 7 As long as the value of step is less than the size of the planets array, the step value will be incremented by 1, taking us to the next image in the array. 8 When the index value is greater than the size of the array, it will be reset to 0. 9 Here the JavaScript time is set to call slideShow() every 1.8 seconds. 10 The function slideLink() is defined. Its purpose is to redirect the user to a page de- scribing the planet when he or she clicks its image. Continues EXAMPLE 12.11 (CONTINUED) From the Library of WoweBook.Com ptg 448 Chapter 12 • Working with Images (and Links) 11 The whichimage variable is set to the index value of the current image. After the user clicks the link in the current image, the switch statement is used to match on the index value of that image and then redirect the user to a page describing the planet. By using the back button, the slideshow will continue. 12 The location property of the window object is assigned a Web page describing the planet that the user clicked during the slideshow. 13 Once the page has loaded, the functions preLoadImages() sand StartShow() are called to preload the images and then start the slide show. In this example, there are no controls to start or stop the slideshow. 14 The first image, Jupiter.bmp, is assigned to a link, that when clicked, will call the function, slideLink() to bring up another page with a description of Jupiter. Out- put is shown in Figures 12.23 and 12.24. Figure 12.25 shows an open source Web site that includes example slideshows. Figure 12.23 A clickable image slideshow. Figure 12.24 After the user clicks on the planet Neptune, he or she is redirected to the URL shown here. EXPLANATION From the Library of WoweBook.Com ptg 12.6 Animation and Timers 449 12.6 Animation and Timers On a small but thick pad of paper a boy has drawn a stick man on each page. For each page he draws his stick man in a sightly different position, maybe moving one leg up and an arm down. After filling the pad with as many little stick man pictures as he wants to draw, he goes to his friend and starts rapidly flipping the pages. Voila! He has made a little movie! Although seemingly primitive, this is the idea behind JavaScript animation. Instead of flip- ping through a pad of drawings, the stick man drawings can be scanned into your com- puter as a set of images as shown in Figure 12.26. JavaScript can load the images and then give them the appearance of animation by using a timer that will be set to put a new image on the page at short repeating intervals, similar to flipping the pages of the small pad of paper. With JavaScript, a number of DOM elements (<img />, <div>, etc.) can be moved in the document according to a looping mechanism or an expression tied to a timer. Two JavaScript functions used as timers are setTimeout() and setInterval(), which allow JavaScript code to be executed at set intervals. (We have seen the use of both of these functions throughout this text.) setTimeout(someFunction,500); // calls someFunction() 500 milliseconds from now setInterval(someFunction,500); // calls someFunction() every 500 milliseconds until stopped Figure 12.25 An open source Web site that provides excellent examples of slideshows. From the Library of WoweBook.Com . get excellent JavaScript slideshow libraries that have already been created and free for reuse. The examples provided in this text are to give you some insight on how a simple JavaScript Figure. idea behind JavaScript animation. Instead of flip- ping through a pad of drawings, the stick man drawings can be scanned into your com- puter as a set of images as shown in Figure 12.26. JavaScript. paper. With JavaScript, a number of DOM elements (<img />, <div>, etc.) can be moved in the document according to a looping mechanism or an expression tied to a timer. Two JavaScript