Challenges with Javascript slideshow using arrays

As a newcomer to Javascript, I am facing a challenge with this particular issue. The objective of this script is to rotate through 3 different combinations of text (slide) and images (slideimg) when the previous and next buttons are clicked. Currently, my code works flawlessly when transitioning from element 0 to 2 within the array, in both directions. However, I am struggling with resetting the array back to [0] while the [2] element is active upon clicking the next button. Additionally, I need to assign the active class to [0] and remove it from [2]. Similarly, when the previous button is clicked while [0] is active, I want the array to adjust accordingly. I have experimented with various solutions but haven't been successful in properly displaying the content so far.

const slides = document.querySelectorAll(".slide");
const imgs = document.querySelectorAll(".slideimg");
const prevButton = document.getElementById("larrow");
const nextButton = document.getElementById("rarrow");

var currentSlide = 0;
slides[currentSlide].classList.add("active");
imgs[currentSlide].classList.add("active");

var nextSlide = function(){

    if(currentSlide < 2) {
        currentSlide+=1;
    }

    slides[currentSlide - 1].classList.remove("active");
    slides[currentSlide].classList.add("active");
    imgs[currentSlide - 1].classList.remove("active");
    imgs[currentSlide].classList.add("active");
};

var prevSlide = function(){
    if(currentSlide > 0){
        currentSlide--;
    }

    slides[currentSlide].classList.add("active");
    slides[currentSlide + 1].classList.remove("active");
    imgs[currentSlide].classList.add("active");
    imgs[currentSlide + 1].classList.remove("active");
};

nextButton.addEventListener("click", nextSlide);
prevButton.addEventListener("click", prevSlide);

Answer №1

To begin, start by removing the active class from the current slide. Then update the currentSlide by incrementing it by 1 and using the modulo operator:

const nextSlide = function () {
    slides[currentSlide].classList.remove('active');
    imgs[currentSlide].classList.remove('active');

    currentSlide = (currentSlide + 1) % 3;

    slides[currentSlide].classList.add('active');
    imgs[currentSlide].classList.add('active');
};

For the prevSlide function, follow a similar approach but adjust the currentSlide calculation to:

currentSlide = (currentSlide + 2) % 3;

(The addition of + 2 serves the same purpose as subtraction by 1, ensuring that the correct number is reached when starting from 0. Using modulo with negative numbers does not yield the desired result; for instance, -1 % 2 results in -1, not 2)

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

I'm looking for a way to track the progress of an ajax call. Specifically, I want to know how I

I am currently working on an AJAX call that executes a lengthy PHP script producing 20 different results. I aim to display the progress of each step within the script, such as 1/20 complete, 2/20 complete, 3/20 complete. Last updated on 29-12-2015 at 03:1 ...

What steps can I take to create a slideshow with dynamic animations?

I am trying to create a unique category display by turning it into a slider. When the user clicks on any category, I want it to move to the left and become larger. To see an example of how the sliding effect works, check out this link: slideshow https://i ...

Troubleshooting: Why is my switch-case statement in TypeScript not functioning as expected

Here is a simple switch case scenario: let ca: string = "2"; switch (ca) { case "2": console.log("2"); case "1": console.log("1"); default: console.log("default"); } I am puzzled by the output of this code, which is as follows: 2 1 defa ...

Align title text to the right within the Material Design Card

I have implemented a Material Design (MDL) card to showcase numeric values in the title. However, I am facing an issue where the values are left aligned by default and I want them to be right aligned. Despite trying various styles, they are being ignored ...

The Bootstrap navigation menu is functioning properly when opening, but has an issue when attempting

Creating a mirrored version of an HTML file using NuxtJS, I've included the following code snippet in the Navbar component for my NuxtJS project. <template> <section id="navigation-menu" class="menu menu3 cid-sLhoPz7Ycg" ...

Is there a way to bypass using prompt() in JavaScript without relying on HTML elements?

Currently, I am developing a JavaScript program that involves using the canvas. However, I have encountered an issue with the prompt() function as it has been deprecated in Electron Fiddle which is my current development environment. I need to find an alt ...

Converting document.querySelector into a user-friendly format with React hooks

Is there a way to convert the process of fetching an element using querySelector and adding a reference to a div using document.querySelector into something that can be done with React hooks? import ReactDOM from "react-dom"; import h337 fro ...

Can you explain the distinction between setting abc.p as undefined versus deleting abc.p?

The variable abc is pointing to an object. What distinguishes abc.p = undefined from delete abc.p aside from their return values? ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

What is the method for altering the value of a class within another class?

Check out this piece of code: <div id="one"> <div id="two"> <div class="cell_pad"> </div> </div> </div> How can you instruct CSS to modify the value of class "cell_pad" within the container of id="one"? Th ...

Is there a way to display a message box when the mouse cursor hovers over a text box?

Currently, I have set up 3 text boxes in my project. The functionality I am trying to achieve is when the user clicks on the second text box, the value of the first text box should be displayed in a message box (providing that the validation for the first ...

Fixing display flex with columns of percent width and 1px gap: A step-by-step guide

When displaying flex columns with percent width on a specific width, make sure to leave a 1px gap between them. Check out the screenshot here html, body { margin: 0; padding: 0; } * { box-sizing: border-box; } .wrapper { max-width: 1200px; p ...

Guide on triggering a Bootstrap dropdown using an external button click

I have scoured almost half of the Internet, but I can't seem to find a clear example on how to accomplish this task. There are plenty of "solutions" out there, but nothing has been successful so far. Here is what I have attempted: $('#openner&a ...

What is the best way to implement two distinct global CSS styles for separate pages in Next.js?

I'm looking to give my website a fresh look by creating two different global CSS styles. Is it possible to use one CSS style for the old pages and another for the new pages? ...

Having trouble incorporating custom elements with the document.execCommand function

I have been attempting to insert a custom element into an editable div using the document.execCommand method as described in detail on https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand. However, when I try to add a custom polymer eleme ...

Ways to access elements and their associated values in a JavaScript Array

I'm facing a challenge with a JavaScript array where I need to extract teams (Team A, Team B) and organize them into one array while preserving their order. See below for the current output of the array, as well as the JS code provided and the expecte ...

In CSS, when text within a tab div lacks spaces, it triggers a horizontal scrolling effect

My special css style for the div: .message-body { background: #5181a2; padding: 8px 5px; text-align: justify; } I aim to display this particular text inside the div similar to how 'hello hello' appears on the line above. ...

What criteria need to be met for height: 100% to be displayed correctly?

Although I haven't had the need to use this often, there are times when it proves to be useful... when it decides to cooperate. It's interesting how sometimes the height: 100%; code works perfectly, while other times it seems to fail. It leaves ...

Create 3000 unique squares using a procedural generation method

Looking to build a widget that consists of 3000 squares, but creating them manually would be extremely time-consuming. Does anyone have advice on how to efficiently generate the class .square 3000 times? Additionally, I need to have the ability to customiz ...

Solving Empty Array Element Issues (Using MongoDB, React, and Axios)

I'm currently developing an application that utilizes Axios to make a GET request to a server I've created. Below is the relevant snippet of the server code that might shed light on the issue: app.get("/getScheduledTimes/:day/:stationId", (req, ...