After completing a sequence, it does not reset

I'm working on creating a versatile "slideshow" feature that can be used for various elements. Currently, I am testing it on a div that contains paragraph text taken from my HTML document and represented as container1, container2, and container3. The Clicky() function is triggered by the onclick event on a button.

let slideshow_elements = ["container1", "container2", "container3"];
    for(let i = 1; i < slideshow_elements.length; i++) {
    document.getElementById(slideshow_elements[i]).style.display = "none";
}

let current_slide = 0

function clicky() {
    document.getElementById(slideshow_elements[current_slide]).style.display = "none";

    current_slide = current_slide + 1
    document.getElementById(slideshow_elements[current_slide]).style.display = "block";
}

Once container3 is displayed, containers 1 and 2 are set to display:none. However, when cycling back to container1, it remains hidden. This means that the sequence only works once in the end.

I would greatly appreciate any assistance with this issue.

Answer №1

In order to cycle back to the beginning of the array, utilize a modulo operator:

current_view = (current_view + 1) % slideshow_divs.length;

To demonstrate, here is a comparison table showing the progression of the current_view value with and without the modulo operator:

Without modulo          With modulo
--------------          -----------
      0                      0
      1                      1
      2                      2
      3 (OOB)                0
      4 (OOB)                1
      5 (OOB)                2

If you do not use the modulo operator, the current_view will exceed the array limits once it reaches 3.

Answer №2

To ensure the current_view count resets to 0 once you reach the total number of slides, you can utilize either modulo operations or a simple if conditional based on the .length property of the slideshow_divs array:

let slideshow_divs = ["container1", "container2", "container3"];
    for(let i = 1; i < slideshow_divs.length; i++) {
    document.getElementById(slideshow_divs[i]).style.display = "none";
}

let current_view = 0;

function clicky() {
    document.getElementById(slideshow_divs[current_view]).style.display = "none";

    if (current_view < slideshow_divs.length) {
        current_view = current_view + 1;
    } else {
        current_view = 0;
    }

    document.getElementById(slideshow_divs[current_view]).style.display = "block";
}

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

What steps can I take to enhance my script and prevent the password field from being displayed alongside the username

I am currently working on a script that dynamically displays your username in the Login button as you type it. However, I have encountered an issue where the password is also being displayed, which is unacceptable. Additionally, I would like to enhance my ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

Uncaught TypeError: Cannot create new instances of User - Node.js server not recognizing User as a constructor

I encountered an issue while attempting to save a user to MongoDB database using a post request. The error message "TypeError: User is not a constructor" keeps popping up despite the straightforward setup of my code. I have double-checked but can't se ...

Retrieve the non-empty attributes of a JSON object

I have a function in Typescript that extracts specific values from a JSON data object, some of which may be empty. How can I retrieve only certain data fields? Here is the function: let datosCod; for (let get in Object.keys(transfConsData)) { co ...

Exploring the combination of Express router, Auth0, and plain Javascript: A guide to implementing post-login authentication on a router

After creating a front end with vite using vanilla javascript and setting up a backend with node.js express routes, I successfully integrated swagger for testing purposes. I have managed to enable functionalities such as logging in, logging out, and securi ...

Hide the scroll bar in html/css while keeping the functionality of the arrows intact

Is there a way to remove the scroll bar but still be able to access overflown data using arrows? Any assistance would be greatly appreciated. Thank you in advance. ...

Is it possible to restrict optionality in Typescript interfaces based on a boolean value?

Currently, I am working on an interface where I need to implement the following structure: export interface Passenger { id: number, name: string, checkedIn: boolean, checkedInDate?: Date // <- Is it possible to make this f ...

JavaScript failing to retrieve JSON information from PHP

I seem to be encountering an issue when trying to read JSON data that I create in PHP and send back to my JavaScript. The problem is puzzling me. Here's the PHP code: header("content-type: text/json"); curl_setopt($ch,CURLOPT_URL, $url); curl_setop ...

Can JavaScript be executed from the console while navigating between pages?

I am facing a challenge that I can't find any solutions for online or elsewhere. The task at hand seems straightforward. I am using the Chrome console and attempting to run Javascript code to navigate between pages with pauses in between. It feels lik ...

Divide a list Observable into two parts

In my code, I have an Observable called 'allItems$' which fetches an array of Items. The Items[] array looks something like this: [false, false, true, false] My goal is to split the 'allItems$' Observable into two separate Observables ...

Implementing a Tri-state Checkbox in AngularJS

I've come across various discussions on implementing a 3-state checkbox with a directive or using CSS tricks (such as setting 'indeterminate=true' which doesn't seem to work). However, I'm curious if there's another method to ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

Mapping keys in a react component for efficient sorting

I'm facing some challenges when attempting to reorder keys from a state within my map function in React.. The original output is: monday : {1200: {…}, 1500: {…}, 1800: {…}, 2000: {…}, 2200: {…}, 0000: {…}, 0100: {…}, 0500: {…}, 0600: ...

What is the process of resetting dropdown option values?

Recently, I have encountered an issue with a customized dropdown list in MVC4. I am populating data using AJAX and it is working fine, but the problem arises when the data is not cleared after successfully sending it to the controller. Here's an examp ...

What method is the most effective for preloading images and stylesheets?

One of the main concerns I have is optimizing the load time of my website. I would like to preload images, style sheets, and scripts to ensure a faster loading speed and to prevent users from seeing images loading right before them. Can someone suggest the ...

Utilizing Jquery to enhance table filtering functionality

I created a table listing various places, along with buttons to filter the list. The first filter is based on location (north, east, central, south, west) determined by postcode. The other filter is for "impress" which only displays places with a rating of ...

Ways to verify if an array contains two identical object values?

I am in search of a way to determine whether my array contains duplicate object values or not. Let's say I have the following array of objects: const array = [ { id: "id1", quantity: 3, variation: "red", ...

How to use Sencha Touch to automatically target a textfield on iOS programmatically?

My goal is to implement a pin login feature similar to the ones found on iOS and Android platforms, where users are required to enter a 4-digit pin to proceed. The issue I'm facing is that I want the input field to be automatically selected and the nu ...

disabling a submit button

I am new to coding and need help disabling a button on document load. Can someone assist me with this? Here is my current code snippet: $(document).ready(function() { setTimeout("check_user()", 250); }); Your guidance is greatly appreciated! ...