-1

Example Element I need to animate the change of these 3 characters with the data of the array, when I click this blue button on the right.

This is the HTML code I have written so far.

<div class="cards">
    <div id="card1" class="card">L</div>
    <div id="card2" class="card">A</div>
    <div id="card3" class="card">X</div>
    <a class="btn btn-flat shuffle" href="#" onclick="travelSurprise();"> 
    </a>
</div>

Javascript code is here.

function travelSurprise() {
    let cities = ["NYC", "PTH", "SDN", "KTY", "PRT"];
    let card1 = document.getElementById("card1");
    let card2 = document.getElementById("card2");
    let card3 = document.getElementById("card3");

    for (let i = 0; i < cities.length; i++) {
        setInterval(function shuffle() {
            card1.innerHTML = cities[i].charAt(0);
            card2.innerHTML = cities[i].charAt(1);
            card3.innerHTML = cities[i].charAt(2);
        }, 500);
    }
}

I need to change these three letters when I click the button. Animation should be like the 3 letters will change to all the elements of the array for 3,4 seconds and stop at a random position.

WenukaGTX
  • 155
  • 1
  • 1
  • 9

1 Answers1

0

Try using setTimeout() instead, where the second argument is the 500ms time multiplied by an index of every array item. For the shuffle, use Fisher-Yates algorithm as described here and just do it every time the a is clicked.

  

function shuffle(array) {
  // shuffle your array code
  return array;
}

function travelSurprise(event) {
    
    let cities = ["NYC", "PTH", "SDN", "KTY", "PRT"];
    let card1 = document.getElementById("card1");
    let card2 = document.getElementById("card2");
    let card3 = document.getElementById("card3");
    
    shuffle(cities);

    cities.forEach((city, index) => {
    
      setTimeout(() => {
        
        card1.innerHTML = city.charAt(0);
        card1.innerHTML = city.charAt(1);
        card2.innerHTML = city.charAt(2);
        
  
      }, (index * 500));
    
    });
}
.cards > div {
  
  display: inline-block;
  padding: 2rem;
  background: lightblue;
  border-radius: .3rem;
}

a {
  display: inline-block;
  background: #f2f2f2;
  width: 1rem;
  height: 1rem;
}
<div class="cards">
    <div id="card1" class="card">L</div>
    <div id="card2" class="card">A</div>
    <div id="card3" class="card">X</div>
    <a class="btn btn-flat shuffle" href="#" onclick="travelSurprise();"> 
    </a>
</div>
wscourge
  • 10,657
  • 14
  • 59
  • 80