Programming

Home Search

Random Facts!

Javascript | HTML

14/02/2018


Anybody who saw some of the earlier versions of this website may remeber a section that chose a random fun fact everytime you reloaded the page. I've had some friends of mine beg me to bring that section back into the website somehow, so here's a post detailing the script behind the old 'Random Facts' section.


The first step is simple, you just need to create an array in your section for scripts, like this one.


var facts = [
 'This is a Fact!',
 'Styling this tiny snippet was not easy',
 'HTML, CSS and JS are things'

]


That array is the simple part, it just holds values (in this case facts), that this next piece of script will randomly display every time the script is run.


function newFact() {
var factNumber = Math.floor(Math.random() * (facts.length));
 document.getElementById('factElement').innerHTML = facts[factNumber];
}


Thirdly and lastly you need to add an two peices of HTML in your HTML on the page you would like the fact to display on. These two additions can be seen below.


<body onload="newFact()">


First of all an addition to the '<body>' element, which runs the 'newFact()' function.


<p id="factElement">


And second of all a paragraph element with the ID 'fact Element'. Now I'm aware that this post does not go into any detail about how these things work and I'm hoping to do a follow up going into more depth about how all the script works. Oh and what would this post be if it didn't actually have a working example of this piece of script.



Those words above, were displayed out of a random selection when the page loaded. If you were to refresh the page you would hopefully be able to see a different phrase in that section above. If you want to download the source HTML and Javascript to look and experiment with the script yourself, just click the button below.



Download the Source Code


- Jordan

The Programming Section Begins!

07/02/2018


Yes, a section all about programming, it will be similar to the Development Blog in the form of style but the topic will be about programming! It will make more sense when the first real post is released.


- Jordan