Before we consider some of the plugin's available in jQuery let us see what is involved in building a simple image fader.

HTML for Image Fader

The HTML we will use for the image fader is a simple unordered list as follows:

HTML

<ul class="slideshow">
   <li><img src="../images/wind1.jpg" width="150" height="150" /></li>
   <li><img src="../images/wind2.jpg" width="150" height="150" /></li>
   <li><img src="../images/wind3.jpg" width="150" height="150" /></li>
 </ul>

The >ul< has a class assigned of 'slideshow' to differentiate it from other lists in the document. Within the list are the image that we want to fade between.

CSS for Image Fader

We also need some CSS to change the default behavior of the list.

CSS

.slideshow{
	padding:0;
	margin:0;
	list-style: none;
	position:relative;	
}
ul.slideshow li {
	position:absolute;
	left:0px;
	top:0px;
	display:inline;
}

Doing things over time with setInterval

As we want the images to fade one to another over time we need something to control the timings. Don't forget that you are actually writing Javascript and therefore you can use Javascript constructs alongside jQuery. The setInterval Javascript method calls a function at a user defined setInterval and is perfect for the job.

Syntax
setInterval('callback','duration');

  • callback – Name of the function that is called at the defined set interval.
  • duration – Time between the function identified as the callback. Value in milliseconds.

The setInteval function will return an integer to uniquely identify the setInterval calls. This can be used to clear the setInterval. To do so create a variable to capture the ID of the setInterval. This can be referenced viaithe clearInterval().

Javascript

var intervalID = setInterval("alert('hi!');", 500);
clearInterval(intervalID);

Selecting List Items in Turn with 'nth-child' and length

We need a way of targeting the specific list items one after another to facilitate the fading. The 'nth:child' jQuery selector mentioned earlier in our discussion of custom selectors with help here.

To make our code nice and flexible it would also be useful to know how may images we intended to loop through. The jQuery property 'length' returns the number of elements matched by a selector. Therefore given HTML of:

HTML

    <ul class="myList">
      <li>Apples</li>
      <li>Pears</li>
      <li>Bananas </li>
    </ul>

We could use the jQuery to find out how many list items were in the HTML list.

jQuery

$('ul.myList li').length;

Declaring and Setting the Initial Variables

We now have all the building blocks for our image fader.

Javascript

var fadeDuration=2000;
var displayTime=4000;
var currentIndex=1;
var nextIndex=1;

These variables control the fade duration ('fadeDuration') and the length of time each image is visiable (displayTime) both in milliseconds. The 'currentIndex' tracks the currently visible image whilst 'nextIndex' tracks the next image to fade in.

In the $(document).ready function we set the first image's CSS opacity value to 0. We also assign the first image the CSS class 'show'. This places the image on a 'z-index' of 500 to bring it to the foreground.

CSS

ul.slideshow li.show {
		z-index:500;	
}

jQuery

$(document).ready(function()
        {
$('ul.slideshow li').css({opacity: 0.0});
$("'ul.slideshow li:nth-child("+nextIndex+")'").addClass('show').animate({opacity: 1.0}, fadeDuration);
   	 var timer = setInterval("nextSlide()",displayTime);
        })

Finally a variable of 'timer' is created to hold the ID of the setInterval. The setInterval is constructed to call the 'nextSlide()' function at the duration set in the 'displayTime' variable.

jQuery

function nextSlide(){
          nextIndex =currentIndex+1;
          if(nextIndex> $('ul.slideshow li').length)
          {
             nextIndex =1;
          }
          $("'ul.slideshow li:nth-=>>>>child("+nextIndex+")'").addClass('show').animate({opacity: 1.0}, =>>>>fadeDuration);
          $("'ul.slideshow li:nth-=>>>>child("+currentIndex+")'").animate({opacity: 0.0}, =>>>>fadeDuration).removeClass('show');
          currentIndex = nextIndex;
}

The 'nextSlide' function increments nextIndex by 1 to begin the process of moving on to the next image. If the 'nextIndex' value is greater than the number of images as defined using the 'length' property against the 'ul.slideshow li' then 'nextIndex' is reset to 1 to restart the loop.

Then the image identified with 'nextIndex' and 'currentIndex' as values of 'nth-child' are used in turn to fade in the next image and fade out the previous image. Note the use of chaining to 'animate' and then 'removeClass' against the 'currentIndex' image.

Finally the 'currentIndex' is set to the value of 'nextIndex' for the next iteration.

One Thought to “Building a Simple Image Fader”

  1. Jessica

    Hi There!

    This tutorial is great. Is there a way to make this continuously loop?

    Thanks!

Leave a Comment