I have a tough time with javascript, I don’t know what it is but I cannot get it to work as easily as HTML and CSS. However, I have found a great write up from Florence W Deems that I have altered and it works perfectly.
Before we dive into the code, I have noticed there are many ways to do this and if I am misleading with the information drop a comment below. Alright, let’s get into it.
First things first, in the head section of your HTML document, between the <head> tag and the </head> tag add the following line of code.
<!–Quotes Script–>
<script src=”quotes.js”></script>
Now open a blank document in Notepad++ (or some other text editor) and copy the following code.
<script> var r_text = [
"quote # 1",
"quote # 2",
"quote # 3",
"etc..."
"];
function doText() { var i = Math.floor((r_text.length-1)*Math.random()) document.getElementById(‘quotes’).innerHTML = r_text[i]; }
var myInterval = setInterval(doText, 5000); </script>
(It is important to have each quote in ” ” and have a , if there is another quote after it. I have separated the quotes like this for maintenance later but they can all be on one line between the [ ];
The doText, 5000 is how often the script will fire another quote. This is in milliseconds, change this longer or shorter depending how long in between new quotes you would like.
Now save this file as quotes.js like above.
In the HTML document, find a place where you want the quote to appear and add the following code.
<div id=”quotes”></div>
(Be sure to make whatever id=”” is as the same as in the javascript file where it says document.getElementById(”).
Launch your website and see what happens.
I am thinking of looking into a php include function that pulls and pushes random quotes from a bigger collection and maybe even by category based on the day of the week. Monday obviously being for motivation.
Join The Newsletter
Get occasional emails from me when I publish new projects and articles.