I have a list of facts that I wish to change on page refresh and/or page load.
All the solutions I've e across involve having a button, which I do not want.
function newFact() {
var randomFact = Math.floor(math.random() * facts.length);
document.getElementById('factDisplay').innerHTML = facts[randomFact]
}
So I've got a function that randomly pulls one string (fact) from a list of facts (var facts). I wish to make it such that every refresh/reload of the HTML page will generate a new fact.
EDIT: I called my script using <body onload="newFact()">
. Thanks for all your help!
I have a list of facts that I wish to change on page refresh and/or page load.
All the solutions I've e across involve having a button, which I do not want.
function newFact() {
var randomFact = Math.floor(math.random() * facts.length);
document.getElementById('factDisplay').innerHTML = facts[randomFact]
}
So I've got a function that randomly pulls one string (fact) from a list of facts (var facts). I wish to make it such that every refresh/reload of the HTML page will generate a new fact.
EDIT: I called my script using <body onload="newFact()">
. Thanks for all your help!
- 1 why do you need a button? Call the newFact() function on page load event. – Fabrizio Calderan Commented Jan 21, 2019 at 11:48
2 Answers
Reset to default 5Put it as an IIFE (Immediately invoked function expression) anywhere in your script.
(function newFact() {
var facts = ['Fact 1', 'Fact 2', 'Fact 183'];
var randomFact = Math.floor(Math.random() * facts.length);
document.getElementById('factDisplay').innerHTML = facts[randomFact];
})();
<div id="factDisplay"></div>
IIFEs get (forcibly) executed before any other normal functions in JS. So on every page load/refresh this will be executed first, and show different result each time.
Just put your script at the bottom/footer of your page and call it, like so :
const facts = ["1", "2", "3"];
!function newFact() {
const randomFact = Math.floor(Math.random() * facts.length);
document.getElementById('factDisplay').innerHTML = facts[randomFact];
}();
<div id="factDisplay"></div>