Iterating through and presenting elements of an array sequentially

Is there a way to create a loop or function that can show a new array index every time it is clicked? I attempted using a for loop, but it only displays the first value and then jumps to the last value when clicked again.

var arrow = document.getElementById ('arrow');
var para = document.getElementById ('para');
function textForward (){
  arrow.addEventListener('click', function(){
    var arr = [
     'a','b','c','d'
    ]
    for (var i = 0; i < arr.length; i++)
    para.innerHTML = arr[i]
  });
}

On each click of a button, the above code should display the next value of the array in sequence. For instance, starting with 'a' and progressing to 'b' upon the user's click, followed by 'c' on the subsequent click, and so forth.

Answer №1

Finally cracked the code! Can't believe it took me this long to figure it out..Here's the latest version of the code:

var arrow = document.getElementById('arrow');
var para = document.getElementById('para');
let counter = 0;
function textForward() {
    var arr = [
        'How are you?',
        'Are you Ready to play the Game',
        'Here is how it works',
        'you have three hints to guess what I am thinking',
        'Guess wrong and you are out',
        'simple..let the games begin'
    ];

    para.innerHTML = arr[counter];

    counter++;
}

textForward();

Answer №2

To properly keep track of the current index, it is essential to utilize a global counter as demonstrated below

let arrow = document.getElementById('arrow');
let para = document.getElementById('para');

// Initialize the index
let currentIndex = 0;

let arr = ['a', 'b', 'c', 'd'];

arrow.addEventListener('click', function() {
    para.innerHTML = arr[currentIndex];
    if (currentIndex < arr.length - 1) currentIndex++;
});

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

Is it possible to establish a default URL for the expect() function?

One of the challenges I'm facing is with my Restangular call, which has a baseUrl configured in a specific file as http://localhost:3000/. For example, a call like: Restangular.all("awards").customPOST(award) Actually makes a request to baseUrl+"awa ...

How can I use React Router to maintain the selected list item in the side drawer's state?

Seeking help with react-router and material UI integration. I have successfully integrated routes with my material UI drawer list items, along with custom styling to highlight the selected item upon clicking. However, I am encountering an issue where the s ...

How can you use Jquery's .data() method to find elements with specific values?

I have a button that generates a new drop pin. The pin is contained within a div, and a hidden form input is also created to store the position of the pin when it's dragged. In my jQuery code for creating these elements, I assign a data attribute call ...

When the page reloads, the firebase currentUser variable is found to be

Currently utilizing Firebase for authentication. Prior to making a request to the backend, I always ensure to request the idToken. service.interceptors.request.use(async request => { const token = await firebase.auth().currentUser.getIdToken(); i ...

Producing asynchronous JavaScript events using a browser extension (NPAPI)

Currently in the process of developing a web browser plugin using NPAPI. The issue I am facing is that my plugin requires a worker thread to handle certain tasks, and I need to pass events back to JavaScript as the worker progresses. However, due to the N ...

The output returned by the `reduce()` method cannot be displayed in HTML within a React component when using the `map()` function

Here is the output I am getting: https://i.sstatic.net/E4fK7.png It was generated by the code snippet below: var allblogs = [{ "banner": "41173047269_1594284317134_88820381534.png", "approved_status": 1, "posted_month": "July", "posted_ ...

AngularJS -> Choice for specifying user's decimal format and limit restrictions

Is there a way to use AngularJS to dynamically limit user input to numbers between 0 and 1 with hundredths? For instance, if a user types 0, it should be converted to 0.00; if they type 1, it should become 1.00. I already have a JavaScript function for lim ...

Delays in running multiple jQuery UI effects at the same time

When I implement a show and hide effect with slide on different divs simultaneously on my page, I encounter some lag in the animation. However, I noticed that if I run the show effect only after the hide effect is completed, the lag disappears. I am curiou ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

Sync HTML Videos

Issue: I am currently developing a 3 column layout where certain columns need to remain sticky at the top of the viewport. In one section, I want to use the same video as a background for all 3 columns, with the specific effect of having the middle column ...

What is the correct way to define a variable in Jade?

My app functionality includes exporting user information once they are signed in, allowing the router to update the profile template. However, I am looking to enhance this by dynamically rendering different navigation bars based on the user's sign-in ...

React code is displaying as plain text and the components are not being rendered properly

My latest creation is a component named "componentRepeater" with the main purpose of displaying multiple instances of child components. The props within the "componentRepeater" include properties for the child components, the number of repeats for the chil ...

Converting a single-column table into an array

After reading through numerous posts related to my query, I have yet to find a solution to my problem. Utilizing PHP and MySQLi, I am attempting to extract data from my server. Within my database, I have a single-column table and my aim is to store this ...

Troubleshooting the deployment of a complete full-stack application on Heroku

I have been facing the challenge of deploying my full-stack chatkit messenger app from localhost to production on Heroku. I am encountering a 404 "Not Found" error and unsure about the necessary changes that need to be made in my code for it to run smoothl ...

Double Looping of Ajax on Shopify Order Form

I have an Ajax order form on a product page. Every time the #submit-table button is clicked, it should display a drop-down menu with updated cart information, such as quantities and prices, along with the newly added products. Here's an example of th ...

Experiencing trouble with calculating the total value of an array of objects due to NaN errors

I've been working on developing this web application in VUE.js, but I'm facing an issue with a specific function where I am attempting to sum the values of each object within an array. This is resulting in a NaN (Not a Number) error. Let's t ...

How to add a group of items to a nested document using an index?

I've been working on the code below to create a new subdocument within an existing subdocument. The structure is as follows: User -> (Many Comments) -> (Many Ratings). The rating object is a simple JavaScript object with the format; rating: { ...

Insert a point onto the SVG polygon along the nearest line to the click event

In my React app, there's an SVG polygon element that initially appears as a square but can have new points added by double clicking inside the polygon area. I'm trying to ensure that the point is added to the side of the polygon closest to the p ...

The fetch API is being restricted, however, AJAX and XHR are still operational

I made an API call to a URL shortener and encountered different responses using Fetch, JQuery, and XHR. Why is Fetch returning a 400 error while the other methods work smoothly? Even after trying mode: 'no-cors' and "crossDomain": true in the re ...

What causes the truncation of the backslash in the string "videos1_visualisation.mp4"?

Check out this example of AngularJS code I've created. The factory contains a list of video sources. var videoPlayer=angular.module('videoPlayer',[]) videoPlayer.controller("videoplayer",["$scope","videolist",function($scope,videolist) ...