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.
Asked
Active
Viewed 6,137 times
-3
-
1Can you update your question with the relevant code? – Danny Fardy Jhonston Bermúdez Dec 30 '15 at 15:22
-
Possible duplicate of [Getting random value from an array](http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array) – Xotic750 Dec 30 '15 at 15:41
3 Answers
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
-
[Math.random](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) doesn't take any arguments. – Xotic750 Dec 30 '15 at 15:35
-
This has an an off by one issue, occasionally out of bounds, should not be used – slothstronaut Feb 14 '22 at 01:48
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