Now let's add the code for the script that will animate our images. Add the following code inside the anonymous function below the <body>
tag:
var image = $("#slider img"); var numSlides = image.length; var activeSlide = 0; var speed = 2000; var fade = 1000; var timer = setInterval(rotate, speed); image.eq(activeSlide).show(); function rotate() { activeSlide++; if (activeSlide == numSlides) { activeSlide = 0; } image.not(activeSlide).fadeOut(fade); image.eq(activeSlide).fadeIn(fade); }
The first thing we did was we cached a reference to all the <img>
elements located inside the #slider
element. We'll be referencing it several times, so it is more efficient to only select it from the Document Object Model (DOM) once. For performance reasons, it is generally best to minimize the number of DOM operations that are carried out.
For counting the number of images we used length()
. This counts the number of...