How to make an Automatic Image slider


Image slider, carousel or slideshow whatever you call it, it remains the same and in this tutorial, you'll learn how to make an automatic image slider which turns image automatically.

HTML

First of all, we'll begin by creating a container element with the class slider. Inside div.slider we'll place our images and we'll add class active to our first image.
<div class="slider">
<img src='image1.jpg' class="active">
<img src='image2.jpg'>
<img src='image3.jpg'>
<img src='image4.jpg'>
</div>

CSS

Here we'll set width and height of .slider and its position to relative. Next we'll set max-height and max-width of images to 100%, position to absolute, opacity to 0 and transition to 1 second. and finally we'll set img.active to opacity:1. Switching between opacity 0 and 1 will help us attain a fade effect during tranistion of images.

.slider {
width: 640px;
height: 360px;
position: relative;
}
img {
max-width: 100%;
max-height: 100%;
position: absolute;
opacity: 0;
transition: 1s;
}
img.active {
opacity: 1;
}

JQuery

First, we'll create a function named slider. This function will change the image whenever called. Inside slider() we'll define our first variable $current which is equal to $('.slider img.active') which returns image element with class active inside div.slider. We'll use this variable to check if the image exists or not and if not then will add class active to the first image inside div.slider (though we've added class active but we should not leave loopholes). Then we'll declare our second variable inside else block $next, which is equal to $current.removeClass('active').next() seems pretty complex but it is not it simply removes class active from the current image and then selects next one or next sibling. $next will be used to check next image exists or not if not then we'll add class active to the first image inside div.slider else we'll add class active to next element.
Finally, we'll place this function inside setInterval with the time of 5 seconds i.e image will change every fifth second.
function slider() {
$current = $('.slider img.active');
if ($current.length == 0) {
$('.slider img:first-child').addClass('active');
} else {
$next = $current.removeClass('active').next();
if ($next.length == 0) {
$('.slider img:first-child').addClass('active');
} else {
$next.addClass('active');
}
}
}
setInterval(slider, 5000);

Demo

Video Tutorial