An undefined error was encountered when trying to access x[index] in HTML/CSS/JS slides

I'm a beginner in front end development and I could really use some assistance with this error that's come up

Would you be able to lend me a hand in resolving the issue?

var index = 1; show(index);

function move(n) { show(index = index + n); }

function show(n) { var i; var x = document.getElementsByClassName("slides"); for (i = 0; i < x.length; i++) { x[i].style.display = "none"; } x[index].style.display = "block"; }

.w3-content{max-width:980px;margin:auto}
.w3-center{text-align:center!important}
.w3-btn-floating:hover{box-shadow:0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19)}
.w3-button{color:#000;background-color:#f1f1f1;padding:8px 16px}.w3-button:hover{color:#000!important;background-color:#ccc!important}
.w3-btn,.w3-btn-floating{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}   
.w3-btn-floating{display:inline-block;text-align:center;color:#fff;background-color:#000;position:relative;overflow:hidden;z-index:1;padding:0;border-radius:50%;cursor:pointer;font-size:24px}
.w3-btn-floating{width:40px;height:40px;line-height:40px}
.w3-btn-floating:disabled{cursor:not-allowed;opacity:0.3}.w3-disabled *,:disabled *{pointer-events:none}
.w3-btn-floating{-webkit-transition:background-color .25s,color .15s,box-shadow .25s,opacity 0.25s,filter 0.25s,border 0.15s;transition:background-color .25s,color .15s,box-shadow .15s,opacity .25s,filter .25s,border .15s}
<!DOCTYPE html>
<html>
<body>
<div class="w3-content" style="max-width:400px;position:relative">
<img class="slides" src="https://i.sstatic.net/Qypol.jpg" style="width:100%">
<img class="slides" src="https://i.sstatic.net/yU7fs.jpg" style="width:100%">
<img class="slides" src="https://i.sstatic.net/xxLmR.jpg" style="width:100%">
<img class="slides" src="https://i.sstatic.net/YiIiQ.jpg" style="width:100%">
<a class="w3-btn-floating" style="position:absolute;top:45%;left:0" onclick="move(-1)">❮</a>
<a class="w3-btn-floating" style="position:absolute;top:45%;right:0" onclick="move(1)">❯</a>
</div>
</body>
</html>

Answer №1

Your JavaScript code needs to account for the changing index based on the length of the slides each time the right and left buttons are clicked.

When clicking the right button, the index increases, so you need to reset it to the first image or slide using this condition: if (n > x.length) {index = 1}
Conversely, when decreasing the images or slides (left button), use this condition: if (n < 1) {index = x.length}.

Below is the modified JS code to address this issue:

var index = 1;
show(index);

function move(n) {
  show(index = index + n);
}

function show(n) {
  var i;
  var x = document.getElementsByClassName("slides");
  if (n > x.length) {index = 1}    
  if (n < 1) {index = x.length} 
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";  
  }
  x[index-1].style.display = "block";  
}

Fiddle(View):

var index = 1;
show(index);

function move(n) {
  show(index = index + n);
}

function show(n) {
  var i;
  var x = document.getElementsByClassName("slides");
  if (n > x.length) {index = 1}    
  if (n < 1) {index = x.length} 
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";  
  }
  x[index-1].style.display = "block";  
}
/* CSS styles omitted for brevity */
<!DOCTYPE html>
<html>
<body>
<div class="w3-content" style="max-width:400px;position:relative">
<img class="slides" src="https://i.sstatic.net/Qypol.jpg" style="width:100%">
<img class="slides" src="https://i.sstatic.net/yU7fs.jpg" style="width:100%">
<img class="slides" src="https://i.sstatic.net/xxLmR.jpg" style="width:100%">
<img class="slides" src="https://i.sstatic.net/YiIiQ.jpg" style="width:100%">
<a class="w3-btn-floating" style="position:absolute;top:45%;left:0" onclick="move(-1)">❮</a>
<a class="w3-btn-floating" style="position:absolute;top:45%;right:0" onclick="move(1)">❯</a>
</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

Issue encountered: Document not being saved by Mongoose, error message received: "MongoClient connection must be established"

Currently, I am attempting to establish a connection with MongoDb using mongoose. Below is the code snippet that I have implemented for this purpose: controller.js const conn = mongoose.createConnection(db, { useNewUrlParser: true, ...

What could be causing the preloader to fail in my React application?

I am developing a React App with Redux functionality, and I am looking to implement a preloader when the user clicks on the "LoginIn" button. To achieve this, I have created a thunk function as follows: export const loginInWithEmail = (email, password) =&g ...

Interactive table featuring a delete row function

Upon adding a new row to my table with user input and delete button functionality, I encountered an issue where the button only works after the second click. In my Add() function, I use a counter variable i to assign IDs to rows, incrementing it by 1 for e ...

running a for loop for multiple onclick events

I have a situation where I need to create an onclick event that performs multiple tasks. There is a button labeled Add Item in the image below. When clicked, it should add the HTML code shown below: var addItemHTML = '<tr class="hold-item&quo ...

Using Jquery Ajax to Send Data with ASP Core ActionResult

Is there a way to successfully submit a form data using Jquery Ajax in Asp Core? AJAX CODE if (contactForm.valid() == true) { var formData = new FormData(); formData.append("Name", contactForm.find("input[name='Name']& ...

Adjust the text color when hovering with the style tag

When it comes to customizing the color of a link on hover, CSS makes it simple with code like this: .myId:hover{ color:green; } But what if you're using inline styles? Is there a way to achieve the same effect without just plain HTML and CSS? & ...

When the HTML content matches a specific value, initiate a click event to trigger

Can anyone help me troubleshoot? I've tried multiple methods but can't seem to get it right. Here's a breakdown of what I'm attempting to accomplish: #info-NUMBER-btn shows Click to display more information. #info-NUMBER CSS is set t ...

The uploaded file is not stored in Node.js within the destination folder

script.js var multer = require('multer'); var fileUpload = (req, res) => { var document = req.files.file; var storage = multer.diskStorage({ destination:(req, files, cb)=> { cb(null, '/uploads') ...

Having trouble with JQuery Draggable in FireFox only working in an iFrame? Learn how to set the ViewPort to fix

Having trouble with jQuery UI Draggable in FireFox 33.0.2: I followed the example code, but it doesn't seem to be working. The scripts are running, CSS classes are added, event bindings are in place, but dragging won't work. I noticed that when ...

Arrange the 2D array in JavaScript by utilizing both categories

Looking to organize a 2D array based on two specific criteria: [ [ "the,", 3 ], [ "who,", 3 ], [ "take,", 4 ], [ "over,", 4 ], [ "world,", 5 ] ] Sort by number in ascending order Then arrange alphabe ...

Having trouble with ES6 in Canvas - why won't my code display correctly?

I'm currently working on developing a painting app using ES6. However, I'm facing issues with the positioning and line drawing on the canvas. The lines are not being drawn in the correct position; for example, the top-left corner is formed when ...

The CSS property for restricting white-space to nowrap is not functioning as

Having a div with multiple child divs floating left can be tricky. To prevent them from breaking, setting them to display:inline-block and white-space:nowrap seems like the solution. However, in some cases this may not work as expected. If your goal is to ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

Closure-compiler and its peculiar pre-codeyntax

When it comes to minimizing my JS code, I typically rely on the online closure compiler available at . Recently, I've been attempting to incorporate this process into PhpStorm using "External tools," but I seem to be encountering a strange issue. Ever ...

How to display an array with JSON objects in Angular 4

Looking to display specific data from an array in my .html file that originates from my .ts file: myArray: ["03/05/2018", "2:54", "xoxo", "briefing", "your", [{ "Id": "1", "Time": "20:54", "Topic": "mmmmm", "GUEST1": { "Role": "HS" ...

What is the best way to eliminate repetitive values from a dynamic select dropdown using Javascript?

Struggling to solve this issue with no success. Essentially, we are populating a select element with values from the service it's being retrieved from. However, duplicates are appearing in the select. The code responsible for this behavior is shown be ...

Another option instead of using componentWillMount to set up axios interceptors in React

Here's my current dilemma. The challenge I'm facing involves registering interceptors on the request and response of my axios instance to handle errors. To achieve this, I've created a wrapper component called withErrorHandler that manages ...

Using Vue to pass data from a forEach loop to the href attribute

Currently, I am dealing with a situation in Vue where I have an array that I need to loop over and render anchor elements for each iteration. The array is passed in as one of my props. Despite trying various methods, I find that the solutions I come up wit ...

Converting lists to JSON format in a C# web form

Utilizing JSON.stringify, I have implemented textbox autocomplete for a web-form that suggests city names based on user input. The goal is to retrieve relevant city names from the database and display them as suggestions in the autocomplete feature after t ...

Ways to delete a particular query parameter from a URL in Next.js

http://localhost:3000/?search=test&type=abc&category=xyz When searching for "test" along with the type and category, the URL changes accordingly to the link provided above. return router.push( { pathname: `/`, query: { ...