Welcome to the beginner-friendly tutorial on building a Random Quote Generator with JavaScript! In this project, we'll create a simple app that fetches random quotes from an API and displays them dynamically. This project is an excellent way to learn API integration and UI updates in JavaScript.
Before we begin coding, let's set up a workspace for our project. Think of this folder as your digital canvas, where you'll keep all the project files organized.
Create a new folder on your computer to store all your project files. You can name it "random-quote-generator".
On Windows:You'll need a text editor to write your code. We recommend Visual Studio Code, which is free and beginner-friendly.
We need three essential files for our project:
To create these files:
🎯 Success Check: You should now have:
👉 Tip: If something's not working, try restarting VS Code or creating the files using the "File → New File" menu.
Let's start by building the HTML structure for our random quote generator. HTML is like the foundation of our app.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Quote Generator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Random Quote Generator</h1>
<div class="quote-container">
<p id="quote">Click the button to get a random quote.</p>
<button id="get-quote">Get Quote</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Let's break down the HTML structure:
<div class="container">
: This is the main container for our app.<h1>Random Quote Generator</h1>
: The title of our app.<div class="quote-container">
: The container for the quote and the button.<p id="quote">Click the button to get a random quote.</p>
: The paragraph element for displaying the quote.<button id="get-quote">Get Quote</button>
: The button for fetching a new quote.<script src="script.js"></script>
: Includes the JavaScript file for handling the app's functionality.Save your "index.html" file. Now we have the basic HTML structure in place. In the next step, we'll add some styling to make it look nice!
CSS is like the paint and brushes we use to make our app visually appealing. Let's add some styles to our random quote generator.
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
box-sizing: border-box;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 400px;
text-align: center;
}
h1 {
margin: 0 0 20px;
font-size: 1.5rem;
}
.quote-container {
margin-top: 20px;
}
#quote {
font-size: 1.2rem;
margin-bottom: 20px;
text-align: center;
}
button {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
transition: background-color 0.3s ease;
}
button:hover {
background-color: #0056b3;
}
Let's understand the CSS rules we just added:
body
: Sets the default font, removes margins and padding, and centers the content on the screen..container
: Styles the container with a white background, padding, rounded corners, and a shadow.h1
: Styles the title with a larger font size and margin..quote-container
: Adds margin to the quote container.#quote
: Styles the quote paragraph with a larger font size and margin.button
: Styles the button with a blue background, white text, no border, padding, border-radius, cursor, and transition for smooth changes.button:hover
: Changes the background color of the button on hover.Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the styled quote generator.
Now, let's add JavaScript to make our app interactive! We'll start by handling user interactions and fetching quotes from the API.
First, we need to select the HTML elements we want to work with. We'll select the button and the paragraph element.
// Selecting HTML elements
const getQuoteButton = document.getElementById('get-quote');
const quoteElement = document.getElementById('quote');
Here, we're using the getElementById
method to select the HTML elements with specific IDs.
Next, we'll add an event listener to the button to handle the click event. We'll fetch a random quote from the API and update the UI.
// Handling button click
getQuoteButton.addEventListener('click', () => {
fetch('https://quotes-api-self.vercel.app/quote')
.then(response => response.json())
.then(data => {
quoteElement.textContent = `${data.quote} - ${data.author}`;
})
.catch(error => { console.error('Error fetching quote:', error); });
});
In this part, we're using the addEventListener
method to listen for the 'click' event on the button. We fetch a random quote from the API, update the UI with the quote and author, and handle any errors that might occur during the fetch request.
Now, let's put everything together. If you've been following along and pasting the code into your "script.js" file, it should look like this:
// Selecting HTML elements
const getQuoteButton = document.getElementById('get-quote');
const quoteElement = document.getElementById('quote');
// Handling button click
getQuoteButton.addEventListener('click', () => {
fetch('https://quotes-api-self.vercel.app/quote')
.then(response => response.json())
.then(data => {
quoteElement.textContent = `${data.quote} - ${data.author}`;
})
.catch(error => { console.error('Error fetching quote:', error); });
});
Let's ensure our quote generator looks great on various devices by adding responsive design using CSS media queries.
@media (max-width: 600px) {
.container {
width: 90%;
}
#quote {
font-size: 1rem;
}
button {
padding: 8px 16px;
font-size: 0.9rem;
}
}
Let's understand the CSS rules we just added:
@media (max-width: 600px)
: A media query for screens up to 600px wide (e.g., mobile phones)..container
: Adjusts the width of the container to 90% for better visibility on smaller screens.#quote
: Adjusts the font size of the quote for better readability on smaller screens.button
: Adjusts the padding and font size of the button for better readability on smaller screens.Save your "styles.css" file. Now, if you resize your browser window or view the quote generator on different devices, you'll see the layout adapt to different screen sizes.
In the next step, we'll add final touches to the quote generator.
Let's add the final touches to our quote generator to ensure it is fully functional and visually appealing.
.container {
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
button {
transition: background-color 0.3s ease, transform 0.3s ease;
}
button:hover {
transform: scale(1.05);
}
Let's understand the CSS rules we just added:
.container
: Adds a more pronounced shadow to the container for a better visual effect.button
: Adds a transition effect for background color and transform to the button.button:hover
: Scales the button slightly larger on hover to create a subtle zoom effect.Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the final touches in action.
Congratulations! You've completed the JavaScript project, "Random Quote Generator." You've learned how to create a simple app that fetches random quotes from an API and updates the UI dynamically. You've also learned the basics of API integration and UI updates in JavaScript.
Feel free to continue customizing your quote generator and exploring more JavaScript techniques. Happy coding! 🚀