I am having trouble displaying a random word from an array on my webpage. Whenever I click the button, it shows undefined and the console.log of randIndex gives me NaN.
I've been trying to solve this issue but I can't seem to figure out what's wrong. The goal is for the mealBtn to display a meal item above itself when clicked. However, it only shows undefined in the DOM. What baffles me the most is that if I run an initialize function on window.load, everything works perfectly as expected.
//load a menu item when the window loads
window.addEventListener('load', init);
const mealBtn = document.getElementById('mealBtn');
const currentMeal = document.getElementById('current-meal');
const message = document.getElementById('message');
const menu = [
'Macaroni',
'Burgers',
'Chili',
'Breakfast',
'Chicken',
'Take Out?'
];
function init(){
showMeal(menu);
}
mealBtn.addEventListener('click', showMeal);
//display a random meal from the menu array
function showMeal(menu){
const randIndex = Math.floor(Math.random() * menu.length);
currentMeal.innerHTML = menu[randIndex];
message.innerHTML = 'How about this?';
message.style.color = '#003b6f'
};
When I click the button, I expect to see a menu suggestion right above it on the DOM. It successfully displays the content on the initialization function when the window is loaded but fails to do so when the button is clicked.