custom slider in javascript code example
Example: custom image slider javascript
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
* {
box-sizing: border-box;
}
.Slide {
display: none;
}
img {
vertical-align: middle;
width: 100%;
height: 400px;
}
.slideContainer {
max-width: 600px;
position: relative;
margin: auto;
}
.prevBtn,
.nextBtn {
position: absolute;
top: 50%;
width: auto;
padding: 10px;
background-color: rgb(255, 255, 75);
color: rgb(50, 0, 116);
font-weight: bolder;
font-size: 18px;
}
.nextBtn {
right: 0;
}
.Caption {
color: #fbff09;
font-weight: bold;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
font-size: 25px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
.Navdot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: rgb(54, 5, 117);
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.selected,
.Navdot:hover {
background-color: #d9ff00;
}
@media only screen and (max-width: 450px) {
.prevBtn,
.nextBtn,
.Caption {
font-size: 16px;
}
}
</style>
</head>
<body>
<div class="slideContainer">
<div class="Slide">
<img src="https://images.pexels.com/photos/3540375/pexels-photo-3540375.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" />
<div class="Caption">Photo 1</div>
</div>
<div class="Slide">
<img src="https://images.unsplash.com/photo-1558981001-5864b3250a69?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" />
<div class="Caption">Photo 2</div>
</div>
<div class="Slide">
<img src="https://images.unsplash.com/photo-1584910758141-f7993f9e203d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=667&q=80" />
<div class="Caption">Photo 3</div>
</div>
<a class="prevBtn">❮</a>
<a class="nextBtn">❯</a>
</div>
<br />
<div style="text-align:center">
<span class="Navdot" onclick="currentSlide(1)"></span>
<span class="Navdot" onclick="currentSlide(2)"></span>
<span class="Navdot" onclick="currentSlide(3)"></span>
</div>
<script>
document.querySelector(".prevBtn").addEventListener("click", () => {
changeSlides(-1);
});
document.querySelector(".nextBtn").addEventListener("click", () => {
changeSlides(1);
});
var slideIndex = 1;
showSlides(slideIndex);
function changeSlides(n) {
showSlides((slideIndex += n));
}
function currentSlide(n) {
showSlides((slideIndex = n));
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("Slide");
var dots = document.getElementsByClassName("Navdot");
if (n > slides.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = slides.length;
}
Array.from(slides).forEach(item => (item.style.display = "none"));
Array.from(dots).forEach(
item => (item.className = item.className.replace(" selected", ""))
);
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " selected";
}
</script>
</body>
</html>