Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  26] [ 3]  / answers: 1 / hits: 5996  / 9 Years ago, wed, september 9, 2015, 12:00:00

I am looking to create a kind of magic eight ball website. This is an example of what I am thinking of. How can I write code to mimic this random answer effect?


More From » html

 Answers
2

Sure, you can select random answers from an array and display them. Suppose you have an array named answers. You can select one at random like this:



var answer = answers[Math.floor(Math.random() * answers.length)];


Then you can insert the answer into an element named answerContainer, for example:



document.getElementById('answerContainer').innerHTML = answer;


Here is a demonstration:





var answers = [
'Maybe.', 'Certainly not.', 'I hope so.', 'Not in your wildest dreams.',
'There is a good chance.', 'Quite likely.', 'I think so.', 'I hope not.',
'I hope so.', 'Never!', 'Fuhgeddaboudit.', 'Ahaha! Really?!?', 'Pfft.',
'Sorry, bucko.', 'Hell, yes.', 'Hell to the no.', 'The future is bleak.',
'The future is uncertain.', 'I would rather not say.', 'Who cares?',
'Possibly.', 'Never, ever, ever.', 'There is a small chance.', 'Yes!'];

document.getElementById('answerButton').onclick = function () {
var answer = answers[Math.floor(Math.random() * answers.length)];
document.getElementById('answerContainer').innerHTML = answer;
};

p, input, button {
font-family: sans-serif;
font-size: 15px;
}
input {
width: 200px;
}

<p> How can I help you today? </p>

<input type=text placeholder=enter a question></input>

<button id=answerButton> Answer me </button>

<p id=answerContainer></p>




[#34303] Tuesday, September 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rohan

Total Points: 403
Total Questions: 93
Total Answers: 105

Location: Trinidad and Tobago
Member since Mon, Jul 13, 2020
4 Years ago
;