I used a code on this site to shuffle an array in Javascript. However, it only shuffles the array when the page refreshes and not when the button is clicked on. I need 'Cars' within the brackets() to make the array shuffle but it's the main problem here. How do I fix this?
//var clickMe = ["Lamborgihni", " Ferrari", " Porsche"," Buggatti", " Toyota", " Mercedes", " Audi"," BMW"];
document.getElementById("finished").onclick = function() {
randomCars(Cars)
};
function randomCars(Cars) {
var i = Cars.length,
t, j;
// While there remain elements to shuffle...
while (0 !== i) {
// Pick a remaining element...
j = Math.floor(Math.random() * i);
i -= 1;
// And swap it with the current element.
t = Cars[i];
Cars[i] = Cars[j];
Cars[j] = t;
}
return Cars;
}
var answer1 = ["Lamborgihni", " Ferrari", " Porsche", " Buggatti", " Toyota", " Mercedes", " Audi", " BMW"];
answer1 = randomCars(answer1);
//console.log(answer1);
document.getElementById("finished").innerHTML = answer1;
var firstPlace = document.querySelector(".firstPlace");
var secondPlace = document.querySelector(".secondPlace");
var thirdPlace = document.querySelector(".thirdPlace");
if (answer1 = answer1.length) {
firstPlace.textContent = answer1[0] + " Came 1st Place";
}
<h1>Car Racing Game with a Table</h1>
<p>We have 8 cars participating in a race. The aim of this exercise is to randomize the order in which the cars finish the race. Pressing a button should trigger this event.</p>
<div class="carRace">
<p id="finished"></p>
</div>
<button onclick="randomCars(Cars)" type="button" id="clickMe">Click Me</button>
<p class="firstPlace"></p>
<p class="secondPlace"></p>
<p class="thirdPlace"></p>