Having trouble with my JavaScript onClick function in obtaining the expected output value

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">&#10094;</a>
      <a id="nextbtn" class="next">&#10095;</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>

Answer №1

  1. The utilization of let was necessary in the initial for loop.
  2. The assignment of s based on n was not correctly implemented.

The provided code should function as expected and fulfill your requirements.

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 (let 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) {
    n = 0;
  }
  s = n;
  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";
}
showSlides(0); // Display the first slide by default
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">&#10094;</a>
      <a id="nextbtn" class="next">&#10095;</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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the IDs of the previous and next list items if they exist?

Hey there friends, I've hit a roadblock and could really use your help. I'm trying to figure out how to get the previous and next list items in a specific scenario. Let's say I have a ul with three li elements, and the second one is currentl ...

Unable to fetch Twitter data using AJAX

Currently, I'm working on a web page that aims to display tweets from a specific city based on a user's search topic. The Twitter request is being sent successfully, with a response code of 200, and the response data is visible in the Chrome deve ...

The POST request is not functioning. An error has occurred: Unable to retrieve response data - no content is available for the preflight request

Having trouble making a post request from my client side to the back-end. Even with the new movie hardcoded, it keeps returning an error stating that there was a failure in loading the response data. Below is the code for the front-end: //Fetch request t ...

Update article translation dynamically in Vue without needing to refresh the page

ArticleController public function index() { $locale = Lang::locale(); // $locale = Lang::getLocale(); $articles = Article::withTranslations($locale)->get(); return $articles; } resources/assets/js/pages/articl ...

Tips for optimizing background images for various screen sizes?

I'm experiencing an issue with my background image where the head is being cut off on larger screens. Is there a way to ensure that the entire picture is always displayed regardless of screen size? The initial property for background-size is set to co ...

Prevent dropzone from refreshing the page

For the past few days, I have been scouring the internet for solutions on how to prevent a page from automatically reloading after an upload. Despite finding various methods, I have been unsuccessful in resolving this issue. Although I am following the st ...

Display loading images using the Bxslider plugin

Currently, I have implemented a Bxslider on my website with the following HTML markup: <div class="slide"> <a target="_blank" href="#"><img src="image.jpg"/></a> </div> <div class="slide"> <a target="_blank" href= ...

Issue with calling jqPlot function in jQuery causing malfunction

I am perplexed as to why the initial code functions correctly while the second code does not. <a data-role="button" href="#page2" type="button" onClick="drawChart([[["Test1",6],["Test2",5],["Test3",2]]])"> <img src="icons/page2.png" inline style ...

What is the best way to extract the lowest and highest values from a `rangpicker` when using a price slider?

Can someone provide assistance on retrieving the minimum and maximum value after a mouse-drag operation? Kindly review the code snippet below: <div id="double_number_range" style="margin-top: 13px;"></div> <script type="text/javascrip ...

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...

React does not recognize the event.which property as undefined

I'm currently working on limiting the input in a text field to only numbers, backspace, or space. I've tried checking before I set the state and preventing the default behavior of the event in other cases, but I can't seem to find the event. ...

How can I customize the visibility toggles for the password input field in Angular Material?

Currently immersed in the Angular 15 migration process... Today, I encountered an issue with a password input that displays two eyes the first time something is entered in the field. The HTML code for this is as follows: <mat-form-field appearance=&qu ...

Tips for organizing user information to generate a pie chart

My goal is to dynamically collect user input data from form input textboxes to create a pie chart when the submit button is clicked. Currently, I have a test version set up with fixed values displayed here: <form style="margin-bottom: 50px;"> 1 val ...

PHP: Retrieve and store XML data for one-time use within a session

I have implemented Simplexml within a class to load specific nodes from my xml file into html. <?xml version="1.0" encoding="UTF-8"?> <note> <item> <title>Reminder</title> </item> <item> ...

Error occurred while trying to parse JSON due to an abrupt ending

While attempting to reinstall one of my old vue projects on my new computer (running Windows 10) using npm, I encountered the following error: npm ERR! Unexpected end of JSON input while parsing near '...n":"0.8.1","devDepend' ...

Ensure the initial value in the dropdown menu is automatically set to the first value in VueJs

How can I set the first value of my time object as the default value for my dropdown in Vue? I want the first value to be pre-selected when a user enters the website, but currently only display the value without actually selecting it. time Object:- { &quo ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

modifying the href attribute of a tag is determined by the value of window

I'm working on a jQuery snippet that detects the current window's URL and, depending on the href value of the window, changes the href of an anchor tag. Here's what my code looks like so far: (function($) { "use strict"; $(document).re ...

Step-by-step guide to importing a directory in ReactJS

Is there a way to create an input that can upload an entire directory with all its folders intact? I attempted the following code: <input ref={wrapperRef} id="file-upload" name="file-upload" type="file" ...

My jquery seems to be malfunctioning -- can't quite figure out what the issue is

My jquery is not working as expected! It was functioning fine when I included the script directly in the HTML file, but now that I have moved it to a separate file, it's not working. I even tried changing the file name, but no luck. //HTML file loca ...