Tell us what’s happening:
I am writing a script using jquery to randomly pull 5 entries from a list array, and sometimes when I click the button to generate the entries I get a console error “TypeError: eachCard is undefined” even though the variable eachCard
is defined in the code.
Your code so far
$(document).ready(function(){
//all possible cards and their point values
var cardSource=[
{
card: "You remembered to do your homework",
points:"5"
},
{
card:"Dang that was funny!",
points:"10"
},
{
card:"You got your rival in trouble",
points:"20"
},
{
card:"You forgot to tie your shoelaces",
points:"30"
},
{
card:"Quit playing with your food",
points:"7"
},
{
card:"Rolled a brilliant success",
points:"18"
},
{
card:"Narrowly avoided expulsion",
points:"25"
},
{
card:"That was embarassing",
points:"13"
}
];
$('#cardButton').click(function(evt){
//prevent browser's default action
evt.preventDefault();
var randomCards = [] //an empty array to store our random card stack
//fill it up!
while(randomCards.length < 5){
var sourceLength = cardSource.length;
var randomNumber= Math.floor(Math.random()*sourceLength);
var r = randomNumber + 1;
if(randomCards.indexOf(r) === -1) randomCards.push(r);
}
var timeAnimation = 500;
var cardContainer = $('#cardContainer');
//fadeout on callback
cardContainer.fadeOut(timeAnimation, function(){
//make sure the stack is empty
$( "li" ).remove();
//set a new stack of cards using the indices we picked in randomCards
$.each(randomCards, function(i, v) {
var eachCard = cardSource[v];
var cardStack = $('#cardStack');
cardStack.append('<li><p class="cardValue">' + eachCard.card + '</p><p class="points">' + eachCard.points +' points</p>'+'</li>');
});
//fadein animation.
cardContainer.fadeIn(timeAnimation);
});
});//end cardButton function
});//end document ready
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:62.0) Gecko/20100101 Firefox/62.0
.