Home > Blockchain >  Random Alert Box Content
Random Alert Box Content

Time:01-18

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.

  1. The last comma in your rockTalk array adds 1 to the length of the array. In turn, this means that the random generator sometimes returns undefined.

  2. var randomItem = rockTalk[Math.floor(Math.random() * rockTalk.length)] works fine, but you have placed it outside of the georgeSpeaks 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.

  3. document.body.innerHTML = randomItem doesn't do anything so I have removed it.

  4. I have re-worked your code into a more conventional style.

  5. Semi-colons are not required in JavaScript - they indicate the end of a statement - but they make code more readable.

  6. 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>

  • Related