Building a Custom Slider with Vanilla JavaScript
Overview: In this blog post, we'll explore how to create a custom image slider using vanilla JavaScript. We'll cover the basics of defining the HTML structure and CSS styles for the slider, as well as implementing the JavaScript code to handle the sliding animation and the navigation buttons.
Code Snippet:
html
<div class="slider">
<div class="slides">
<img src="image1.jpg" alt="Slide 1" />
<img src="image2.jpg" alt="Slide 2" />
<img src="image3.jpg" alt="Slide 3" />
<img src="image4.jpg" alt="Slide 4" />
</div>
<button class="prev">Previous</button>
<button class="next">Next</button>
</div>
<style>
.slider {
position: relative;
overflow: hidden;
width: 100%;
}
.slides {
display: flex;
width: 400%;
transition: transform 0.5s ease-in-out;
}
.slides img {
width: 25%;
height: auto;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: transparent;
border: none;
font-size: 24px;
color: white;
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
</style>
<script>
const slides = document.querySelector('.slides');
const prev = document.querySelector('.prev');
const next = document.querySelector('.next');
let currentIndex = 0;
const handlePrev = () => {
currentIndex = currentIndex === 0 ? 3 : currentIndex - 1;
slides.style.transform = `translateX(-${currentIndex * 25}%)`;
};
const handleNext = () => {
currentIndex = currentIndex === 3 ? 0 : currentIndex + 1;
slides.style.transform = `translateX(-${currentIndex *
25}%)`;
};
prev.addEventListener('click', handlePrev);
next.addEventListener('click', handleNext);
</script>
No comments:
Post a Comment