Random Quotation Generator

Project Description

Uses the Fetch API to retrieve a randomly-choosen selection of ten inspiring quotations.

Setting up the base web page

Your first task is to set up the base web page.

  1. In your portfolio/js folder, create a new sub-folder named quotes.
  2. Download the following file to this new portfolio/js/quotes folder.   index.html
  3. Give it the filename index.html.
  4. Update the website logo, favicon, <title> tag and the <footer> with your own details.

This file contains all the necessary HTML and CSS for this project.

Note: Ensure the file is linked to the lunadoge.min.css stylesheet, and not the older lunadoge.css version.

Adding the JavaScript code

At the bottom of your index.html web page, just before the closing </body> tag, add the following JavaScript code within a <script> tag.

document.querySelector("#btn-quotes").addEventListener("click", fetchRandomNumQuotes);

async function fetchRandomNumQuotes() { 
   await fetch('https://type.fit/api/quotes')

      .then(response => {
         if (response.status !== 200) {
            console.log('Error Status Code: ' + response.status);
            return;
         }
         response.json().then((data) => {
            console.log(data);
            const lowerNum = getRandomInt(0, data.length-10);
            const upperNum = lowerNum + 9; 
            let html_block = "";
            for (i= lowerNum; i < upperNum; i++) { 
               html_block = html_block + `<div class="col-3"><p><span>“</span>${data[i].text}<span>”</span></p><h3>${data[i].author}</h3></div>`;
               document.getElementById("quotes-box").innerHTML = html_block;
            }
         });
       })

       .catch(error => {
          // handle any error
      });

}

function getRandomInt(min, max) {
   min = Math.ceil(min);
   max = Math.floor(max);
   return Math.floor(Math.random() * (max - min + 1) + min); 
}

Add some CSS styling in the style tag in the head of the web page

Save your finished file with the name index.html in the portfolio/js/quotes sub-folder.