today I decided to learn how to make sliders (carousel) , I must point out that I am pretty much new to JavaScript.
First I tried to think how I should code that myself, I had no inspiration or ideas whatsoever. (Just pointless ideas) , so I went to watch youtube in hope of "enlightment" and there were solutions, but a bit too advanced for me to understand.(and long)
After that I googled "how to make sliders" and I found something simpler on w3schools. At first, I was a bit confused, but after a while I started to understand it bit by bit, of course, not totally.
So here comes the question, can someone explain me what each line does and how it affects the others? Or if there is a better and easier method, I would love to hear it.
Here is the javascript file(followed by CSS and HTML), I only modified a few variable names to understand them better and replaced var with let or const:
let index = 1;
showDivs(index);
function plusSlide(value) {
showDivs(index += value);
}
function showDivs(value) {
let i;
let slider = document.getElementsByClassName("slides");
if (value > slider.length) {
index = 1;
}
if (value < 1) {
index = slider.length;
}
for (i = 0; i < slider.length; i++) {
slider[i].style.display = "none";
}
slider[index - 1].style.display = "block";
}
.sliders {
display: flex;
width: 400px;
height: 200px;
}
input[type="button"] {
width: 100px;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="css.css" type="text/css">
</head>
<body>
<input type="button" value="Back" onclick="plusSlide(-1)">
<input type="button" value="Forward" onclick="plusSlide(+1)">
<div class="sliders">
<img src="https://via.placeholder.com/150/0000FF/FFFFFF/?text=image1" width="400" height="200" class="slides">
<img src="https://via.placeholder.com/150/FF00FF/FFFFFF/?text=image2" width="400" height="200" class="slides">
<img src="https://via.placeholder.com/150/00FFFF/FFFFFF/?text=image3" width="400" height="200" class="slides">
</div>
<script src="scripts.js"></script>
</body>
</html>