Project Description
Uses the Fetch API to retrieve a randomly-choosen selection of ten inspiring quotations.
You can view a completed version of the project here.
Your project folder
In your portfolio/js folder is a folder named quotes that contains all the files you need for this JavaScript project.
In VS Code, open the project’s index.html web page and ensure the hyperlinks and personal details have been correctly updated.
Adding the JavaScript code
Follow the steps below to add the JavaScript code to the index.html file.
- Scroll down the web page until you see an empty pair of opening <script> and closing </script> tags.
- Click inside the empty pair of tags and paste the JavaScript code below.
// Add a click event listener to the button with the ID "btn-quotes". // When the button is clicked, the function fetchRandomNumQuotes will be executed. document.getElementById("btn-quotes").addEventListener("click", fetchRandomNumQuotes); // Asynchronous function to fetch random quotes and display them on the page. async function fetchRandomNumQuotes() { try { // Await the response from the fetch request to the quotes API. const response = await fetch('https://type.fit/api/quotes'); // Check if the fetch request was not successful (status code not 200). if (response.status !== 200) { // Log the error status code to the console and exit the function early. console.log('Error Status Code: ' + response.status); return; } // Await and parse the JSON response from the fetch request. const data = await response.json(); // Logging the raw data and its length for debugging or inspection purposes. console.log(data); console.log(data.length); // Initialize an empty string to accumulate HTML content. let html_block = ""; // Loop through the first 15 items of the data array. for (let i = 0; i < 15; i++) { // Check if the current quote's author is not specified and set it to "Anonymous" if true. if (!data[i].author) { data[i].author = "Anonymous"; } // Remove ", type.fit" from the author's name if present. data[i].author = data[i].author.replace(", type.fit", ""); // Append a formatted string containing the quote text and author to the HTML block. // This uses template literals to insert variables directly into the string. html_block += `<div class="col-3"><p><span>“</span>${data[i].text}<span>”</span></p><h3>${data[i].author}</h3></div>`; } // Insert the accumulated HTML content into the element with the ID "quotes-box". document.getElementById("quotes-box").innerHTML = html_block; } catch (error) { // Log any errors that occur during the fetch operation. console.log('Error fetching quotes:', error); } }
- Save your index.html file.
- Display the file in a web browser and verify it works correctly.
Uploading your project to GitHub
Upload the quotes folder as a sub-folder of the portfolio/js folder on your GitHub account.