In this article I will explain with an example, how to build a simple
JavaScript auto image rotator using timed image swap technique.
HTML Markup
The following HTML Markup consists of:
div – Container for images.
img – For displaying images.
<div id="dvRotator">
<img alt="" src="/Image/Hydrangeas.jpg" height="150" width="200" />
<img alt="" src="/Image/Koala.jpg" height="150" width="200" />
<img alt="" src="/Image/Lighthouse.jpg" height="150" width="200" />
</div>
Auto Image Rotator using JavaScript
Inside the
window.onload JavaScript event handler, first an HTML DIV and images are fetched.
Then, a FOR loop is executed each image is displayed and counter variable is set to 1.
Inside the
setInterval JavaScript function, a FOR loop is executed and each image is displayed.
Then, a check is performed if counter is equal to length of image then counter value is set to 0.
Finally, image time interval is set to 1000.
<script type="text/javascript">
window.onload = function () {
var rotator = document.getElementById("dvRotator");
var images = rotator.getElementsByTagName("img");
for (var i = 1; i < images.length; i++) {
images[i].style.display = "none";
}
var counter = 1;
setInterval(function () {
for (var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
images[counter].style.display = "block";
counter++;
if (counter == images.length) {
counter = 0;
}
}, 1000);
};
</script>
Screenshot
Demo
Download