Our Todo List
We will start by looking at our expected final product and listing out our Todos.
- Generate Quote Button and assign it an onclick function.
- Display Quote and its author.
For the styling I used code from this Codepen illustration and did a few edits.
You could copy the following html and css.
Our project has three sections; the quote display area, author display area and the generate new quote button. the generate new quote button is not really an html button as it does not include the <button> tag. However it serves us the same purpose as a normal html button. I got its source code from this codepen.
Don't forget to create the css folder and place your main.css file in it.
With the above code; you should see the following screen on your browser when you refresh your index.html.
However, when you click on the button the browser returns an error because you have not created the onclick function yet.
On to the spicy part
It is now time for us to work on our quotes and display a quote on the screen each time the generate quote button is clicked.
We need an array of quotes so that we are able to access them through their index in the array. I copied my quotes after searching for popular quotes on Google.
Next we will add our array of quotes that will be randomly selected and displayed. The quote array has several objects with quote and author keys alongside their respective values.
Now let's add the function to be called when the button is clicked.
Let's break it down before writing it down:
We need to generate a random number that is going to be used as the random index. To generate a random number we use math.random(). The math.random function returns a random decimal between 0 and 1.
We however need a larger number as we cannot display just O and 1 and the decimals in between. Therefore we multiply the value returned by the math.random() by the length of our array. This gives us a number between 0 and the length of our array.
This way we don't have less random indices and at the same time we don't generate indices that are not within our array. However, this returns a decimal. But we need a whole number as our random index. Therefore we use Math.floor() to round off the value returned to the nearest whole number. Voila! we have our randomIndex.
We now need to display our random quote and it's author in our html. For this we will use the HTML DOM innerHTML property. This is used to either change or get the value of an HTML element. But this time we are assigning a value to the two elements with the id "quote" and "author".
The full code is here.
Thank you for reading through. I hope it has been of help to you. You could comment below on what you think about the article and what you would like to see in the next articles.