I am a beginner in programming.
I’ve an image slider using HTML and CSS and using JavaScript.
I have a problem with this script for displaying slides i want to display from right to left
The problem is, that the sliding is working from right to left, but not right to left.
Here’s the code:
const sliders = document.querySelectorAll(".slider");
// console.log(slides);
var counter = 0;
sliders.forEach((slide, index) => {
slide.style.left = `${index * 100}%`;
// slide.style.bottom = `${index * 100}%`;
});
const nextSlide = () => {
if (sliders.length == counter + 1) {
counter = 0;
} else {
counter++;
}
transformSlide();
};
const previousSlide = () => {
if (counter == 0) {
counter = sliders.length - 1;
} else {
counter--;
}
transformSlide();
};
const transformSlide = () => {
sliders.forEach((slide, index) => {
slide.style.transform = `translateX(-${counter * 100}%)`;
// slide.style.transform = `translateY(${counter * 100}%)`;
});
};
*{
padding:0;
margin:0;
box-sizing: border-box;
}
.sliders{
width: 80%;
height: 600px;
margin: auto;
margin-top: 100px;
box-shadow: 0px 0px 3px grey;
position: relative;
overflow: hidden;
}
.slider{
width: 100%;
height: 100%;
position: absolute;
transition: 1s;
}
.nav{
text-align: center;
margin-top:20px;
}
.nav button{
font-size: 25px;
color: rgb(72, 71, 0);
padding: 10px;
background-color: orange;
border-radius: 20%;
}
.nav button:hover{
background-color: green;
cursor: pointer;
}
.nav button:active{
background-color: rgb(196, 196, 220);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="./style.css" rel="stylesheet" >
<title>Slider of Image</title>
</head>
<body>
<div class="sliders">
<img src="https://picsum.photos/id/320/1200/600" class="slider">
<img src="https://picsum.photos/id/321/1200/600" class="slider">
<img src="https://picsum.photos/id/322/1200/600" class="slider">
<img src="https://picsum.photos/id/323/1200/600" class="slider">
<img src="https://picsum.photos/id/324/1200/600" class="slider">
</div>
<div class="nav">
<button onclick="previousSlide()">Previous</button>
<button onclick="nextSlide()">Next</button>
</div>
<script src="./script.js"></script>
</body>
</html>
2
Answers
Thank you for your interest in my question, but the code is not working
Try to modify the transformSlide function to properly handle negative values
In the previousSlide function, make sure that you’re decreasing the counter correct:
And in the nextSlide function: