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

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

Guide to setting up an automated process in PHP

When setting up a tournament interface on my page: Users utilize functions like fopen() and fwrite() to create tournaments. The created tournaments must only start after a specific time, for example, 1 hour. This delay allows other users to join the tour ...

Defining the active element in the menu using JavaScript

I need help with my navigation menu: <ul> <li id="active"><a href="/">Home</a></li> <li><a href="/about/">About Us</a></li> <li><a href="/services/">Our Services</a>< ...

Looking to display a div with both a plus and minus icon? Having trouble getting a div to show with left margin? Need assistance hiding or showing div text

Can someone please review this source code? Here is the demo link: http://jsfiddle.net/bala2024/nvR2S/40/ $('.expand').click(function(){ $(this).stop().animate({ width:'73%', height:'130px' }); $( ...

v-for triggers actions on every div

Yesterday I posed a question regarding the removal of a custom truncate filter in Vue. If you missed it, you can find the original question here: Deleting a Vue custom filter when mousing over However, what I failed to mention is that I am utilizing a v- ...

Is there a way to convert HTML into a structured DOM tree while considering its original source location?

I am currently developing a user script that is designed to operate on https://example.net. This script executes fetch requests for HTML documents from https://example.com, with the intention of parsing them into HTML DOM trees. The challenge I face arise ...

Issue with showing Angular directive

I've been working on implementing an angular dropdown list with Bootstrap. The functionality includes a directive that allows the user to select a menu option from the dropdown and receive an alert message. To see the implementation in action, I have ...

Create a substitute for Object.seal, Object.freeze, and Object.preventExtensions applications

Is there a way to freeze an object's existing properties while still allowing new ones to be added? I can't seem to find any built-in functionality for Object.freezeExisting(), so maybe it's worth considering implementing it, possibly even w ...

Access a specific JSON value using AngularJS

When using AngularJS to read a specific JSON value, I encountered the following issue: $http({method: 'GET', url: urlVersion}). success(function(data, status, headers, config) { console.log("success data " + status); $scope.ext = data.ve ...

Is it possible for me to identify the original state of a checkbox when the page first loaded, or the value it was reset to when `reset()` was

When a webpage is loaded, various input elements can be initialized as they are declared in the HTML. If the user modifies some of the input values and then resets the form using reset(), the form goes back to its initially loaded state. I'm curious, ...

Optimal approach for handling large JSON files

I am in possession of a JSON file containing approximately 500 lines. I am hesitant to simply dump this JSON data into the end of my Node.JS file as it doesn't seem like the most efficient approach. What alternatives or best practices can be recommend ...

add the closing </div> tag using jquery only

Having a slight issue here, it seems that jQuery is being overly clever. Within my HTML code, I am attempting to insert this string into a div container: </div><div class="something"> You'll notice that the closing tag comes first, foll ...

Creating atomic controller actions in Sails.js: A guide to optimizing your controller functions

If I am looking to perform multiple operations within a Sails.js controller, how can I ensure that these actions are atomic to maintain the correctness of the results? This includes not only database operations but also various Javascript processing tasks. ...

Guide to executing a fetch request prior to another fetch in React Native

I am currently working on a project using React Native. One issue I have run into is that all fetch requests are being executed simultaneously. What I actually need is for one fetch to wait until the previous one has completed before using its data. Speci ...

Conceal a column within a table by double-clicking

I'm working on a project with a table, and I'd like to implement a feature where a column hides when double-clicked. I've seen various solutions for hiding columns on Stack Overflow, but I could use some guidance on where to add the ondblcli ...

Utilizing react.js and passing props as parameters in recursive functions

When using recursion, I encountered an issue where I am unable to pass the props parameter: class App extends React.Component { constructor(props) { super(props); this.state = { visible: this.props.root, a:this.props.a }; } toggle(){ thi ...

Error: Unable to access the 'clearAsyncValidators' property as it is undefined when running Jest tests on an Angular component

Encountering an Error While Testing Components with Jest Here is my code block for onClickLogin() method: onClickLogin() { if(this.loginForm.valid) { this.api.getLoginData().subscribe(res => { const user = res.find(a => { ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...

What is the best way to manage div visibility and sorting based on selections made in a select box?

Explaining this might get a bit confusing, but I'll do my best. In my setup, I have two select boxes and multiple divs with two classes each. Here is what I am trying to achieve: When an option is selected, only the divs with that class should be ...

Retrieve the id for the chosen user name within a function that contains an array of objects

const userList = [ {name:"jonh" ,id:EAD1234}, {name:"peter" ,id:EAD1235}, {name:"matt" ,id:EAD1236}, {name:"henry" ,id:EAD1237}, ] In the array above, there are various users with their respective IDs. The goal is t ...