Home > Software design >  How can I Loop through Array Items and Change Value every time Button is clicked
How can I Loop through Array Items and Change Value every time Button is clicked

Time:11-23

How can I run through array items and Loop through every single time whenever I clicked the button and change the value based on the array Items that is inside the array.

<img src="/assets/a-puppy-1642002.jpg" alt="Random Pictures" id="images">
<div>
     <button id="img-changer">Random</button>
</div>   


document.getElementById('img-changer').addEventListener('click', (btn) =>{
    let src = "src";
    let srcpath = "/assets/"
    let imgstock = [
        'Birds in Flowers Romantic Seamless Pattern Vector Background.jpg',
        'bucegi-mountains-1641852.jpg',
        'cat-and-kittens-1641561.jpg',
        'happy-doggy-1642001.jpg',
        'landscape-waterfall-1641818.jpg',
        'new-dawn-1641926.jpg',
        'river-of-the-world-1642010.jpg',
        'annie-at-home-1641997.jpg',
        'a-puppy-1642002.jpg'
    ]   
    
    document.getElementById('images').setAttribute(src, `${srcpath}${imgstock}`);
})

I'd like to run it indefinitely, like when is in the end of the Array item it will back to imgstock[0] then run again.

I've tried forEach and Map method

imgstock.forEach(img => {
        for(i = 0; i < img.toString(); i  ){
            let newImg = img[i];
        }
    })

It returns undefined. If my question seems so dumb, I apologize.

And if there's anything that can shorten or methods that can reduce my code. Please let me know. Thanks.

CodePudding user response:

The simplest Solution for this would be having a active counter variable which changes on every click, keeping tack of which image is being displayed.

// Active Image Index Holder
let activeImage = 0;

document.getElementById('img-changer').addEventListener('click', (btn) => {
  let src = "src";
  let srcpath = "/assets/"
  let imgstock = [
    'Birds in Flowers Romantic Seamless Pattern Vector Background.jpg',
    'bucegi-mountains-1641852.jpg',
    'cat-and-kittens-1641561.jpg',
    'happy-doggy-1642001.jpg',
    'landscape-waterfall-1641818.jpg',
    'new-dawn-1641926.jpg',
    'river-of-the-world-1642010.jpg',
    'annie-at-home-1641997.jpg',
    'a-puppy-1642002.jpg'
  ]

  // Incrementing the Active Image Index If it Overflows, then Resetting to 0
  activeImage = activeImage   1 < imgstock.length ? activeImage   1 : 0;

  document.getElementById('images').setAttribute(src, `${srcpath}${imgstock[activeImage]}`);
})
<img src="/assets/a-puppy-1642002.jpg" alt="Random Pictures" id="images">
<div>
  <button id="img-changer">Random</button>
</div>

  • Related