In this article I will explain with an example, how to build a simple Image Slider with Fade effect using jQuery.
In this Image Slider, the Background Image of HTML DIV will be automatically changed at certain period.
The URL of the Images will be stored in a JavaScript Array and then using JavaScript setInterval function, the Background Image of HTML DIV will be dynamically changed (swapped) periodically using jQuery.
Simple Image Slider with Fade effect using jQuery
The following HTML Markup consists of an HTML DIV element. There are some images placed inside a folder named Images.
The names of all images present in the Images folder are stored in a JavaScript Array.
Inside the jQuery document ready event handler, a counter variable is initialized to 0 and the first image from the JavaScript array is set as Background Image for the HTML DIV.
Then using JavaScript setInterval method, the counter variable is incremented and the next image from the JavaScript array of images is set as Background Image for the HTML DIV.
After the last image is fetched, then again the counter is re-initialized to 0. This way infinitely the HTML DIV’s Background image is changed with jQuery Fade In and Fade Out animation.
<div id="dvImage" style="height: 308px; width: 410px">
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var images = ["Chrysanthemum.jpg", "Desert.jpg", "Hydrangeas.jpg", "Jellyfish.jpg", "Koala.jpg", "Lighthouse.jpg", "Penguins.jpg", "Tulips.jpg"];
$(function () {
var i = 0;
$("#dvImage").css("background-image", "url(images/" + images[i] + ")");
setInterval(function () {
i++;
if (i == images.length) {
i = 0;
}
$("#dvImage").fadeOut("slow", function () {
$(this).css("background-image", "url(images/" + images[i] + ")");
$(this).fadeIn("slow");
});
}, 1000);
});
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads