vac
April 18, 2020, 12:58am
1
I watched a YouTube video and wrote it down. Unfortunately I can’t find my mistake even after two hours. I need your help.
This little code is supposed to be a slider. The slider stops after I have clicked through the pictures, but at the first / last picture it does not jump on the others. -.-
sanity
April 18, 2020, 7:08am
2
Can you include your code, instead of the image of code?
vac
April 19, 2020, 8:56pm
3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="carousel-container">
<div class="carousel-slide">
<img src="/img/5.jpg" id="lastClone" alt="">
<img src="/img/1.jpg" alt="">
<img src="/img/2.jpg" alt="">
<img src="/img/3.jpg" alt="">
<img src="/img/4.jpg" alt="">
<img src="/img/5.jpg" alt="">
<img src="/img/1.jpg" id="firstClone" alt="">
</div>
</div>
<button id="prevBtn">Prev</button>
<button id="nextBtn">Next</button>
<script src="app.js"></script>
</body>
</html>
* {
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
.carousel-container {
width: 60%;
margin: auto;
border: 5px solid black;
overflow: hidden;
}
.carousel-slide {
display: flex;
width: 100%;
height: 500px;
}
const carouselSlide = document.querySelector('.carousel-slide');
const carouselImages = document.querySelectorAll('.carousel-slide img');
// Buttons
const prevBtn = document.querySelector('#prevBtn');
const nextBtn = document.querySelector('#nextBtn');
// Counter
let counter = 1;
const size = carouselImages[0].clientWidth;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
// Button Listener
nextBtn.addEventListener('click', () => {
if (counter >= carouselImages.length - 1) return;
carouselSlide.style.transition = "tranform 0.4s ease-in-out";
counter++;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
});
prevBtn.addEventListener('click', () => {
if (counter <= 0) return;
carouselSlide.style.transition = "tranform 0.4s ease-in-out";
counter--;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
});
carouselSlide.addEventListener('transitionend', () => {
if (carouselImages[counter].id === 'lastClone') {
carouselSlide.style.transition = "none";
counter = carouselImages.length - 2;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
if (carouselImages[counter].id === 'firstClone') {
carouselSlide.style.transition = "none";
counter = carouselImages.length - counter;
carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
}
});
Sorry for the late reply.