I tried to shuffle array of cards
it doesnt work I dont know why
function shuffle(array) {
let curr = array.length, rand;
while (curr != 0) {
rand = Math.floor(Math.random() * curr);
curr--;
[array[curr], array[rand]] = [array[rand], array[curr]];
}
return array;
}
const shuffleButton = document.querySelector(".shuffleButton");
shuffleButton.onclick = shuffle(cards);
2
Answers
The issue with your code is that you’re calling the
shuffle
function directly in the click event handler for theshuffleButton
, rather than passing in a function reference. This means that the shuffle function is executed immediately when the page is loaded, rather than waiting for the button to be clicked.To fix this, you can wrap the call to
shuffle
inside an anonymous function that gets executed when the button is clicked, like this:This will ensure that the shuffle function is only executed when the button is clicked.
Also, make sure that the cards array is defined and contains the cards you want to shuffle.
It’s possible that the click event is not being registered for the button element. You can try using the addEventListener() method instead of assigning the onclick property, like this:
You’re immediately invoking the shuffle function on click of the button. Instead, you should provide a callback function to the onclick property that will be called when the button is clicked.
modify your code to make it work, Updated Code is
The callback function gets all the .card elements on the page, shuffles them using the shuffle function, and replaces the existing cards in the
.container
element with the shuffled cards.