Random Playing card generator only fires once!

Hi guys

I have created a simple event where you click a button and you get a random playing card.

However, it only works once! You have to reload the page to get it work again, because after one click you can’t generate any more random cards.

Can someone help? This is so frustrating

/* Card Trick */

let cardArr = [‘./card1.jpeg’, ‘./card2.png’, ‘./card3.png’];
let randomCard = document.getElementById(‘randomCard’);

let randEq = Math.floor(Math.random() * cardArr.length);
let randCard = cardArr[randEq];

function pickCard() {
randomCard.src = randCard;
}

cardReveal.addEventListener(‘click’, pickCard);

Hi, try re-assigning the value of randCard in the pickCard() function, e.g:

let cardArr = [’./card1.jpeg’, ‘./card2.png’, ‘./card3.png’];
let randomCard = document.getElementById(‘randomCard’);

let randEq = Math.floor(Math.random() * cardArr.length);
let randCard = cardArr[randEq];

function pickCard() {
randEq = Math.floor(Math.random() * cardArr.length);
randCard = cardArr[randEq];
randomCard.src = randCard;
}

cardReveal.addEventListener(‘click’, pickCard);
1 Like

wow thank you… it works. But why do I have to repeat all that stuff inside the function when I’ve defined it beforehand?

You don’t have to, you could wrap the following in a function which returns the array element:

function returnNewCard() {
let randEq = Math.floor(Math.random() * cardArr.length);
return cardArr[randEq];
}

function pickCard() {
randomCard.src = returnNewCard();
}

An easier method might be to just remove the randEq and randCard declarations entirely and just edit your function as follows:

function pickCard() {
randomCard.src = cardArr[Math.floor(Math.random() * cardArr.length)];
}

Hope that makes sense!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.