Is there a way to cycle through an array with each click?

I am currently working on implementing a slider feature that enables users to navigate through different pieces of information by clicking on arrows. However, I have encountered an issue where one arrow works correctly (forward), but the other arrow does not respond at all. Additionally, when attempting to click the left arrow multiple times, it triggers an uncaught TypeError and renders both arrows non-functional. Any guidance or advice would be greatly appreciated.

Below is the snippet of code in question:

const xhr = new XMLHttpRequest();



xhr.onload = function () {
    const episodes = JSON.parse(this.responseText);

    let i = 1
    arrowRight.addEventListener('click', () => {
        if (i < episodes.length) {
            epiNum.innerHTML = `Episode ${episodes[i].episode}`
            epiTitle.innerHTML = `${episodes[i].title}`;
            epiDescription.innerHTML = `${episodes[i].description}`;
            i++
            console.log(i)

        }
    })
    arrowLeft.addEventListener('click', () => {
        if (i <= episodes.length) {
            i--
            epiNum.innerHTML = `Episode ${episodes[i].episode}`;
            epiTitle.innerHTML = `${episodes[i].title}`;
            epiDescription.innerHTML = `${episodes[i].description}`;
            console.log(i)
        }

    })
}

xhr.open('GET', 'data/episodes.json', true);
xhr.setRequestHeader("content-type", "application/json");
xhr.send();

Answer №1

It appears that there is a missing check to determine if you are at the beginning or end of the array.

arrowRight.addEventListener('click', () => {
    if (i < episodes.length) {
        epiNum.innerHTML = `Episode ${episodes[i].episode}`
        epiTitle.innerHTML = `${episodes[i].title}`;
        epiDescription.innerHTML = `${episodes[i].description}`;
        if (i + 1 == episodes.length) {
          i = 0
        } else {
          i++
        }
        console.log(i)

    }
})

A similar check will be needed for the left arrow as well.

Furthermore, it may be necessary to adjust the value of I.

let i = 0;

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

Can you pinpoint the weak wiring in this AngularJS function?

I am currently studying AngularJS and I suspect there may be a glitch in my page. On the page, there is a TEXTAREA where I have typed 'aaa'. The TEXTAREA is linked to an ng-model named input. The following AngularJS code aims to monitor external ...

Do we need to use the "new" keyword when using ObjectID in a MongoDB query

Recently, I was immersed in a Typescript web project that involved the use of MongoDB and ExpressJS. One particular task required me to utilize a MongoDB query to locate and delete a document using the HTTP DELETE method. However, during the process of exe ...

I'm having difficulties getting onokayscript to function properly alongside the AJAX modal popup extender

I am having trouble with the onokay script not working in my code. My goal is to trigger the asp button click event when the okay button is clicked, and if the cancel button is clicked, the button click event should not be triggered. Below is the code th ...

Trouble with populating Ext.grid.Panel from ExtJS4 JSON data

Despite researching various posts on the topic, I am still facing issues. Even after attempting to create a Panel with minimal data, I cannot seem to make it work. This problem is really puzzling me. Below is the code snippet that I am currently working wi ...

Dynamic display of images using AJAX and ASP.NET web service

I'm currently facing an issue while trying to generate and retrieve an image of a chart using AJAX to call a Webservice. Despite successfully creating the chart and converting it into an image, I am unable to receive the image back in my AJAX call. H ...

What methods are available for identifying non-operational pointer-events?

According to this resource, Opera 12 does not support pointer-events, causing issues with my website. Interestingly, they do support the property in CSS but don't seem to implement it correctly. Modernizr's feature detection doesn't help in ...

When using jQuery to select elements of a specific class, make sure to exclude the element that triggered the

A dynamic number of divs are generated from a data source. Each div contains an image button and another div with text. While the actual scenario is more complex, we can present a simplified version: <div id="main"> <div id="content_block_1" ...

Whenever I add a new Task in React.js, the date is not visible to me

I'm currently deepening my understanding of React, and I've encountered a roadblock. The issue arises when I attempt to create a Tracking Task - the task is successfully created from the form inputs but the date associated with the new task isn&a ...

Vuejs method to showcase input fields based on form names

I am working on a Vue.js form component with multiple input fields, but now I need to split it into two separate forms that will collect different user input. Form 1 includes: Name Surname Email with a form name attribute value of form_1 Form 2 i ...

Using jQuery, you can store values in a PHP array or session by making an AJAX

Is there a way to store values in PHP array or PHP session using ajax in jQuery? I am trying to send some values via ajax to a PHP page and store them. The issue is that every time the array/session only returns the latest sent value, and not the previous ...

Using Regex in JavaScript to split a string based on a saved pattern

I have a specific sentence to work with: var sentence="example of+a+string"; My goal is to split the string by the + symbol only when it occurs after the word "of". When attempting this with the code: sentence.split(/of(\+)/) The result splits th ...

Analyzing arrays and object key/value pairs based on a specific value in javascript

I want to create a new object with key/value pairs. The new object should include values from an existing key/value object as well as unique values from an array. Here is the array: [{ name: "Computer", name: "Car", name: "House&q ...

Error: Unexpected termination of data in JSON file on line 2, starting at the first character

I keep encountering an error while trying to execute a basic JSON request. Check out the following PHP code that contains the data: <?php header('Content-Type: application/json; charset=utf-8'); $wealth = array( "name" => &q ...

Determining special characters within a string using VueJS

As a newcomer to VueJS, I am currently developing an application that requires a signup and login system. My goal is to inform the user if they have entered a special character such as /[&^$*_+~.()\'\"!\-:@]/. In order to achieve th ...

Django: exploring the power of AJAX and HTTP requests

My English is not very good, but I am facing an issue with Django. Here are my models: class Model1(models.Model): model2 = models.ManyToManyField(Model2) #... class Model2(models.Model): model3 = models.ForeignKey(Model3) #... class Model ...

Please provide the text input for the specified version numbers (1.1, 1.2, 3.0, etc.)

I'm currently working on a form that includes a section for searching by version number: <label class="formLabel">Version</label> <html:text property="valueVersion" styleClass="value" tabindex="11"/> <br/& ...

What steps can you take to ensure that a single-page-application (SPA) is easily searchable within a SharePoint environment

In the process of developing a single-page-application (SPA) with ASP.NET MVC, knouckout, and various other libraries, we have decided to handle routing on the front-end, potentially utilizing crossroads.js. Our use of slickgrid.js allows us to present a w ...

Creating responsive HTML page text and table with the use of JavaScript

Trying to create a responsive webpage has been a bit challenging. I experimented with height,style.height, style.OffsetHeight, etc. but still struggling to dynamically make a square table. Although the code below changes the height, the table's width ...

What is the best way to incorporate dynamic data from Firestore into a function using the `where()` method, while also utilizing the `snap.size` property to accurately count the total number of queries

I am facing an issue while trying to fetch data dynamically from firestore using a where() function. The specific error message I encountered is: TypeError: vaccines is not a function The user collection: [![enter image description here][1]][1] Here a ...

Exploring a React JS option for filtering repeated elements, as an alternative to Angular

While using Angular JS, I came across the 'filter' option within ng-repeat which is useful for live search. Here's an example: <div ng-repeat="std in stdData | filter:search"> <!-- Std Items go here. --> </div> &l ...