Hey there, I've encountered an issue where using a loop to iterate through an array and check the onclick function results in all array elements producing the same result when clicked. The expected behavior is for only the first element's result to be displayed. For example, clicking on dot 3 should only activate the third dot, but instead it activates the first dot (index 0) every time. Can someone please assist with resolving this problem?
var s=0;
var images = ["url(/IMAGES/main.jpg)","url(/IMAGES/main1.jpg)","url(/IMAGES/main2.jpg)"];
var image = document.getElementById("images-container");
var dots = document.getElementsByClassName("dot");
var next = document.getElementById("nextbtn");
var prev = document.getElementById("prevbtn");
for (var i = 0; i < dots.length; i++) {dots[i].onclick = function() {showSlides(i)}}
next.onclick = function() {plusSlides(1)}
prev.onclick = function() {plusSlides(-1)}
function plusSlides(n) {if (s == 0 && n == -1) {s = images.length - 1} else s += n; showSlides(s);}
function showSlides(n) {
if (n == images.length) {s = 0}
for (var i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
image.style.backgroundImage = images[s];
dots[s].className += " active";
}
body {
background-color: grey;
}
images-container {
display: block;
position: absolute;
width: 50px;
height: 400px;
border: 2px solid black;
background-image: url(/IMAGES/main2.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
.prev, .next {
display: flex;
position: relative;
z-index: 1;
top: 80%;
cursor: pointer;
padding: 16px 16px;
color: white;
font-weight: bold;
font-size: 140%;
user-select: none;
}
.prev {
float: left !important;
left: 0;
border-radius: 3px 0 0 3px;
}
.next {
float: right !important;
right: 0;
border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
background-color: rgba(255,255,255,0.4);
}
.dot {
display: inline-block;
position: relative;
cursor: pointer;
height: 15px;
width: 15px;
margin: 1px 2px;
top: 100%;
background-color: rgba(0,0,0,.8);
border-radius: 50%;
transition: background-color 0.6s ease;
}
.active {
background-color: rgba(255,255,255);
}
.dot:hover {
background-color: #717171;
}
<html>
<body>
<div id="images-container" class="images-container">
<p>hey i am the image container.</p>
<div class="prevnext-container">
<a id="prevbtn" class="prev">❮</a>
<a id="nextbtn" class="next">❯</a>
</div>
<div class="dot-container">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
<script type="text/javascript" src="my.js"></script>
</div>
</body>
</html>