For a project I'm working on, I'm trying to make it so that when a button is pressed, an alert box pops up with a message. The message is randomly selected from an array.
I tried this already:
const rockTalk = [
'George is happy. Probably.',
'George is a bit parched, and would be most pleased if you provided him with a drink',
'George is going to sleep now.',
]
var randomItem = rockTalk[Math.floor(Math.random() * rockTalk.length)]
document.body.innerHTML = randomItem
var george = document.getElementById('georgeSprite')
function georgeSpeaks() {
alert('' randomItem)
}
george.onclick = georgeSpeaks()
CodePudding user response:
Your code is almost working. I have made a few changes so that it works.
The last comma in your
rockTalk
array adds 1 to the length of the array. In turn, this means that the random generator sometimes returnsundefined
.var randomItem = rockTalk[Math.floor(Math.random() * rockTalk.length)]
works fine, but you have placed it outside of thegeorgeSpeaks
function. This means that it only runs once and so always produces the same message. I have placed it inside the function which corrects this.document.body.innerHTML = randomItem
doesn't do anything so I have removed it.I have re-worked your code into a more conventional style.
Semi-colons are not required in JavaScript - they indicate the end of a statement - but they make code more readable.
This is your main mistake. Event handlers such as
onclick
require a function reference, which is the function name. Adding brackets executes the function, and in your case the returned value (undefined
) is assigned to the event handler.
Your working code:
const rockTalk = [
'George is happy. Probably.',
'George is a bit parched, and would be most pleased if you provided him with a drink',
'George is going to sleep now.'
];
function georgeSpeaks() {
alert(rockTalk[Math.floor(Math.random() * rockTalk.length)]);
}
var george = document.getElementById('georgeSprite');
george.onclick = georgeSpeaks;
<button id='georgeSprite'>A rock</button>