Photo by Maxim Berg on Unsplash
How to create a basic auto image slider using HTML, CSS and JavaScript :
In this example, we create a basic auto image slider using HTML, CSS, JavaScript.
Table of contents
No headings in the article.
<!DOCTYPE html>
<html>
<head>
<title>Auto Image Slider</title>
<!-- css -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="slider">
<img src="image1.jpg" alt="Image 1" />
<img src="image2.jpg" alt="Image 2" />
<img src="image3.jpg" alt="Image 3" />
</div>
<!-- JavaScript -->
<script src="script.js"></script>
</body>
</html>
CSS :
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.slider {
width: 100%;
height: 400px;
overflow: hidden;
position: relative;
}
.slider img {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slider img.active {
opacity: 1;
}
JavaScript :
const images = document.querySelectorAll('.slider img');
let currentImage = 0;
function nextImage() {
images[currentImage].classList.remove('active');
currentImage = (currentImage + 1) % images.length;
images[currentImage].classList.add('active');
}
setInterval(nextImage, 3000);
Thank you..
ย