Iterate over the array and show the elements only when a click event occurs

I am trying to create a loop through an array (array) and display the elements one by one only after clicking a button (bt). However, when I run this code, it only shows the last element of the array (i.e. honda). Can someone please help me fix this issue?

var hints = document.querySelector(".hint");
                var array = ["Car", "bmw", "mercy", "porsche", "hyundai", "jeep", "honda"];
                var bt = document.querySelector("button");
                for (var i = 1; i < 6; i++){
                    bt.addEventListener("click", function(){
                        hints.textContent = array[i];
                    });
                }
<!DOCTYPE html>
                <html>
                    <head>
                        <meta charset="utf-8">
                        <title>Password</title>
                        <link rel="stylesheet" href="password.css" type="text/css">
                    </head>
                    <body>
                        <h1 class="hint"></h1>
                        <button type="button" name="button">Click me</button>
                        <script src="password.js" charset="utf-8" type="text/javascript"></script>
                    </body>
                </html>

Answer №1

Whenever you click the button, the displayed value is always 'honda' because at that moment the click event occurs, the value of i is set to 6.

Therefore, each click will reveal the value at array[6], which is 'honda'.

Give the following code a try:

let hints = document.querySelector(".hint");
let array = ["Car", "bmw", "mercy", "porsche", "hyundai", "jeep", 
"honda"];
let bt = document.querySelector("button");
let count = 0;

bt.addEventListener('click', () => {
    hints.textContent = array[count];
    console.log('clicked!!');
    count++;

    if (count > array.length) {
        console.log('no more values in the array!!');
        return false;
    }
})

I've also created a codepen showcasing this. Feel free to check it out: https://codepen.io/vishalkaului/pen/EbyjML

Answer №2

Forget about using a for loop. Simply keep track of your count and display the next item on click. Take a look at the revised code snippet below:

var hints = document.querySelector(".hint");
var array = ["Car", "bmw", "mercy", "porsche", "hyundai", "jeep", "honda"];
var bt = document.querySelector("button");
var count = 0;
    bt.addEventListener("click", function(){
       if (count < array.length) {
             hints.textContent = array[count];
            count++;
       }
    });
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Password</title>
        <link rel="stylesheet" href="password.css" type="text/css">
    </head>
    <body>
        <h1 class="hint"></h1>
        <button type="button" name="button">Cick me</button>
        <script src="password.js" charset="utf-8" type="text/javascript"></script>
    </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

Dimensions of Collada Element

This is my first time delving into the world of javascript, WebGL, and Three.js. I successfully added a dae 3D model to my scene, but now I need to determine its size in order to generate objects within it. However, upon adding the dae object, it appeared ...

The handler for errors in DRW consistently generates the message "Error" instead of providing specific information about the issue at hand

FiltersManager.getAllServices({ callback : updateServiceFilter, errorHandler : function(message) { alert(message); } }); Although I throw an exception when an error occurs in th ...

AngularJS and synchronized queueing of API requests

I am attempting to develop a synchronized queue for API requests using AngularJS. class x { public y() { ... restRequest(); } } I have this class, along with a whiteboard canvas. When I drop an entity onto the canvas, the method &a ...

Host app is failing to render shared components in SSR

Encountering an issue while implementing SSR with module federation? Check out my code example Steps to Begin: Run yarn install:all command Execute yarn shell:server:build task Start the server using yarn shell:server:start Initiate remote services with y ...

Achieving successful functionality with position:relative in IE9

Having difficulty with the position: relative property in IE9. Check out this demo for reference: <div style="overflow:scroll;height:120px;"> <table id="table" width="100%"> <tr style="position:relative;background-color:#1b72a4;"> ...

Performing iterations on a matrix of arrays

How can I iterate through an array of arrays in PHP without knowing if it is actually an array or not? Here's an example to clarify: Array ( [0] => Array ( [0] => big [1] => small ) [1] => ...

Exploring the process of iterating through a JSON post response and displaying its contents within image divs

After receiving a JSON post response, I am looking to iterate over the data and display it in image divs. Can anyone provide guidance on how to achieve this using JavaScript? Thank you. Here is the JavaScript code that handles the JSON post response: cor ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

Step-by-Step Guide for Uploading an Entire Folder and Its Contents

I have been working on a code to upload multiple files, but now I am facing the challenge of uploading an entire folder with multiple files and possibly subfolders containing even more files. Currently, I am utilizing JavaScript for obtaining the files and ...

Implement a menu that can be scrolled through, but disable the ability to scroll on the body of the website

When viewed on a small screen, my website transforms its menu into a hamburger button. Clicking the button toggles a sidebar displaying a stacked version of the menu on top of the normal website (position: fixed; z-index: 5;). This sidebar also triggers a ...

How can I ensure a successful redirect to react-router root path after saving to MongoDB in Express?

As a newcomer to React and react-router, I may be making some rookie mistakes in my project. Currently, I am constructing a web application with React and react-router as the frontend server, paired with Express and MongoDB for the backend. To communicate ...

What methods can be used to incorporate animation when the display attribute transitions to none?

Is there a way to add animation in a Vue app when replacing elements? I would like the transition from, for example, clicking on a div with 'Num 1' to the divs with class 'showing' not disappear abruptly but smoothly, such as moving to ...

Issue with updating nested child object reference in Redux state input value

I have a function in redux that updates an object with a specified path and value. The inputs on my page are based on the values in the object stored in state. Whenever the listingObj is modified in redux, I want the DOM to automatically refresh. This i ...

Testing an asynchronous generator function in Jest using unit tests

I need help writing a unit test for a generator function where I am struggling to properly mock a read stream object (ReadStream). Here is the function I'm trying to test: public async *readChunks(file: string, chunkSize: number): AsyncIterableIter ...

sending a pair of variables via jQuery and AJAX

Having difficulty posting two variables using ajax and jquery when a button on a confirm window is pressed. Each variable can be displayed separately, but not both at the same time. UPDATE - Issue resolved. I overlooked including a necessary file. My mist ...

Incorrect credentials trigger an error in Nodemailer

Currently, I am utilizing nodemailer to handle email submissions from a registration form. Below is the code for my registration form: <form action="/registration" method="post"> <h3 class="text-center" style="font-family: 'champagne-l ...

Send the Vue component as an argument to the function

Currently, I am in the process of transferring a project to Vue and utilizing Muuri as a layout manager. In my code, I have the following snippet: grid.add(itemElem, { layout: false, active: false }); The variable itemElem used to be an HTML element c ...

Struggling to understand the concept of utilizing Promises for data retrieval

I'm currently facing an issue with my async function that awaits a GraphQL call. Even though the call returns a Promise containing the desired data, I'm struggling to access it effectively. Below is the snippet of code in question: export async ...

Enhancing Efficiency with Laravel 5: Updating Multiple Data Entries

My Simple Todo App lacks the ability to persist multiple record updates simultaneously. The client-side version can be found here: http://codepen.io/anon/pen/bVVpyN Whenever I perform an action, I send an HTTP request to my Laravel API for data persistenc ...

Issue encountered: Next.js has failed to hydrate properly due to a discrepancy between the initial UI and server-rendered content

Uncertain about the cause of this error? The error seems to disappear when I remove the provided code segment. What is triggering this error in the code snippet and how can it be fixed? <div className="relative flex flex-col items-center pt-[85.2 ...