-3

For the website that I am creating, I am looking to have a random welcome message be generated using a JavaScript array and be displayed on the screen using the innerHTML property. So far, I've created the array with the messages, but I'm stuck on how to select a random one, then insert it using the innerHTML property. Any help would be awesome.

Munesawagi
  • 283
  • 1
  • 6
  • 14

3 Answers3

0

For example

document.getElementById("your-elements-id").innerHTML = "<p>" + yourArray[Math.floor(Math.random() * yourArray.length)] + "</p>";

Put it inside your window.onload or something.

jeoj
  • 633
  • 6
  • 9
0

Try this https://jsfiddle.net/ywnv00xc/1/

const messages = ['message1', 'message2', 'message3', 'message4'];
const randomIndex = Math.round(Math.random()*messages.length);
document.getElementById("your-elements-id").innerHTML = messages[randomIndex];
udnisap
  • 899
  • 1
  • 10
  • 19
0

From MDN:

const getRandomArbitrary = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
};
slothstronaut
  • 921
  • 1
  • 13
  • 15