jQuery: How to Smoothly Change Background Images

jQuery: How to Smoothly Change Background Images
Page content

Using jQuery to Change Images

To smoothly change background images using jQuery, you should either stack more than one image on each other, or store the images in a directory and use a callback function to load another image once the current image fades. I will show you a very simple approach.

You will need a text editor to write the code and a browser to view the HTML page. If you are using Windows, you can use Notepad and save the file with the .html extension.

For the ease of understanding, instead of setting the background image of the web page and then changing it, I will simply create a div element that holds the image that has to be changed. A few images are stacked on upon the other in the div element. Using jQuery, the first image is faded and the next image is shown. This is continued until the last image is shown after which the whole process of fading and showing the next image is started all over again.

The code has been thoroughly commented so that you can easily understand what is happening in each step.

The Code

jQuery: How to Smoothly Change Background Images

jQuery - How to Smoothly Change Background Images 2

jQuery: How to Smoothly Change Background Images

  • pic1
  • pic2
  • pic3

Use the code above to test how it works in your browser. This technique is used in image rotators, animated buttons, etc.