Automatic Image Slider
Image sliders are fascinating and today we will be how can code our own. In this tutorial, we'll be teaching you how to make an automatic image slider which can change images on its own. Basically a really basic version of image slider. Let's begin by gathering things we will need throughout the tutorial.
Things we'll need
- Basic knowledge of HTML, CSS, JavaScript and jQuery
- Lots of will to learn.
Slider Mark Up
At first, begin by creating our main div element with the the class slider which will contain images and first image will have class active as the first image will be displayed by default.
<div class="slider"> <img src='image1.jpg' class="active"> <img src='image2.jpg'> <img src='image3.jpg'> <img src='image4.jpg'> <img src='image5.jpg'> <img src='image6.jpg'> </div>
<div class="slider"> <img src='image1.jpg' class="active"> <img src='image2.jpg'> <img src='image3.jpg'> <img src='image4.jpg'> <img src='image5.jpg'> <img src='image6.jpg'> </div>
CSS
This is were we will set dimensions of slider and its position to relative. Images inside slider are set to max-height height and max-width to 100% to cope up with different aspect ratios of images. Our images are absolutely positioned along with opacity:0 and transition:1s. At last active class is set to opacity:1.
.slider {
width: 350px;
height: 200px;
position: relative;
}
img {
max-width: 100%;
max-height: 100%;
transition: 1s;
opacity: 0;
position: absolute;
}
.active {
opacity: 1;
}
.slider {
width: 350px;
height: 200px;
position: relative;
}
img {
max-width: 100%;
max-height: 100%;
transition: 1s;
opacity: 0;
position: absolute;
}
.active {
opacity: 1;
}
jQuery
Keeping it simple at first step we'll declare our function named slider and inside the function, we'll select the image with class active then we'll check if the element exists or not if not then we'll add class active to the first image element.And if an element exists then we'll remove class active from current element and select next element. Then we'll repeat create an if block. if next image exists we'll add class active to it else we'll add class active to the first image element of the slider.
At the last, we'll call our function inside setInterval.
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, 2000);
At the last, we'll call our function inside setInterval.
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, 2000);