Hey guys im new to javascript and trying to get a better understanding of it, i am trying to make a 8 ball project and currently just to see if it works get it to display in the console but all i recieve is that it is undefined
const predictions = ['Ask again later, Better not tell you now, Cannot predict now, Concentrate and ask again'];
const btn = document.getElementById('btn')
btn.addEventListener('click', function() {
console.log(predictions[randomNumber])
});
function randomNumber() {
return Math.floor(math.random() * predictions.length)
};
body {
background: linear-gradient(to right, #06932d, #000000);
display: flex;
align-items: center;
justify-content: center;
}
#prediction {
position: fixed;
top: 300px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='8-ball.css'rel="stylesheet">
<script defer src="8-ball.js"></script>
<title>8 Ball</title>
</head>
<body>
<div id="title">
<h1>Try the Magic 8 Ball!</h1>
</div>
<div id="btn">
<button>Try Me!</button>
</div>
<div id="prediction">
<p>text</p>
</div>
</body>
</html>
CodePudding user response:
There are a number of issues in your code:
You are missing the parenthesis to call
randomNumber
here:console.log(predictions[randomNumber()]);
Math
always starts with uppercase:return Math.floor(math.random() * predictions.length);
It looks like you want
predictions
to be an array with multiple string elements. Instead, you have a single element with commas in it:const predictions = ['Ask again later, Better not tell you now, Cannot predict now, Concentrate and ask again'];
With everything fixed:
function randomNumber() {
return Math.floor(Math.random() * predictions.length);
}
const predictions = [
'Ask again later.',
'Better not tell you now.',
'Cannot predict now.',
'Concentrate and ask again.'
];
const btn = document.getElementById('btn');
const prediction = document.getElementById('prediction');
btn.addEventListener('click', () => {
prediction.textContent = predictions[randomNumber()];
});
body {
background: linear-gradient(to right, #06932d, #000000);
font-family: monospace;
color: white;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
}
#title {
font-size: 24px;
margin: 0;
}
#box {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#btn {
border: 3px solid white;
font-family: monospace;
background: transparent;
padding: 8px 16px;
border-radius: 4px;
color: white;
font-weight: bold;
font-size: 24px;
margin: 32px 0;
}
#prediction {
font-size: 24px;
margin: 0;
}
<div id="box">
<h1 id="title">Try the Magic 8 Ball!</h1>
<button id="btn">Try Me!</button>
<p id="prediction"> </p>
</div>