Last updated on May 10th, 2022 at 05:19 pm
In this tutorial we will create a simple slideshow using jQuery. For that we need to first define a div with id as slideshow. Also have option to control the speed of the slideshow.
<div id="slideshow">
<img src="img/img1.jpg" alt="" class="active" />
<img src="img/img2.jpg" alt="" />
<img src="img/img3.jpg" alt="" />
</div>
Next CSS to position the images on top of each other and bring the active image to the top level
#slideshow {
position:relative;
height:350px;
}
#slideshow IMG {
position:absolute;
top:0;
left:0;
z-index:8;
}
#slideshow IMG.active {
z-index:10;
}
#slideshow IMG.last-active {
z-index:9;
}
Now we have the structure. Implementing the slideshow comes next and it can be accomplished using jQuery
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ( $active.length == 0 ) $active = $('#slideshow IMG:last');
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 5000 );
});
You might also be interested in Image slideshow with navigation and description
You are free to increase or decrease the speed of the slideshow using , change 5000 to some other value of your choice to control the speed.
setInterval( "slideSwitch()", 5000 );
Note you can add the jQuery section using
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>