dimanche 6 septembre 2020

Follow-Up: How to generate numbers so that there's never a back-to-back array index value?

Need some help in revising the JS to ensure that each click generates a current colors index value different from the previous index value i.e. to ensures that the index numbers are never consecutively repeated as the button is clicked.

<main> 

 <div class="container">
  
   <h2>background color: 
   <span class="color">#f1f5f</span>
   </h2>
   
   <button class="btn btn-hero" id="btn">click me</button>  
   
 </div>   
  
</main>


/* JS */

var colors = ["green", "red", "rgba(133,122,200)", "yellow"];
const btn = document.getElementById('btn');
const color = document.querySelector('.color');


btn.addEventListener('click',  randomColor);

function randomColor() {
  
  var previous = 0;

  var value;


  var max = 4 + (!isNaN(previous) ? -1 : 0);
  value = Math.floor(Math.random() * (max));

  if (value >= previous) {
 
     value += 1; 

  }

  previous = value;

  document.body.style.backgroundColor = colors[value];

  color.innerText = colors[value];

  return value;

}



Aucun commentaire:

Enregistrer un commentaire