Search code examples
javascripthtmlweb-deployment

How to get array element one by one in js


I want to change image and text by clicking the button using the array but the entire array shows when clicking the button

How do I create a loop for this? so that the array element shows one by one.

const arr = [
  {
    img: "https://www.tourmyindia.com/blog//wp-content/uploads/2021/10/Best-Places-to-Visit-in-Bhopal-MP-Sanchi-Stupa.jpg",
    place: "BHOPAL",
    state: "MADHYA PRADESH",
  },
  {
    img: "https://www.tourmyindia.com/blog//wp-content/uploads/2021/10/Best-Places-to-Visit-in-Bhopal-MP-Sanchi-Stupa.jpg",
    place: "MUMBAI",
    state: "MAHARASHTRA",
  },
];

function show(){
let cluster = "";
arr.forEach((item) => {
    cluster =
      cluster +
      ` <h1>${item.place}</h1>
                <div class="vt-bar"></div>
                <h3>${item.state}</h3>
                <div class="arrow">
                    <i class="ri-arrow-left-line"></i>
                    <div class="hz-bar"></div>
                    <i class="ri-arrow-right-line"></i>
                </div>`;
  });
document.getElementById("cluster").innerHTML = cluster;
};

document.getElementById("random").addEventListener("click", function(){
  show();
});

Solution

  • Instead of using foreach loop use index value to get data. Your code should be

    var counter = 0;
    const arr = [
      {
        img: "https://www.tourmyindia.com/blog//wp-content/uploads/2021/10/Best-Places-to-Visit-in-Bhopal-MP-Sanchi-Stupa.jpg",
        place: "BHOPAL",
        state: "MADHYA PRADESH",
      },
      {
        img: "https://www.tourmyindia.com/blog//wp-content/uploads/2021/10/Best-Places-to-Visit-in-Bhopal-MP-Sanchi-Stupa.jpg",
        place: "MUMBAI",
        state: "MAHARASHTRA",
      },
    ];
    
    function show(){
        let cluster = "";
        if (counter<arr.length){
            cluster =
              cluster +
              ` <h1>${arr[counter].place}</h1>
                        <div class="vt-bar"></div>
                        <h3>${arr[counter].state}</h3>
                        <div class="arrow">
                            <i class="ri-arrow-left-line"></i>
                            <div class="hz-bar"></div>
                            <i class="ri-arrow-right-line"></i>
                        </div>`;
            document.getElementById("cluster").innerHTML = cluster;
            counter++;
        }
        
    }
    
    document.getElementById("random").addEventListener("click", function(){
      show();
    });