JavaScript Fetch API Example: HTML, CSS & Vanilla JS Tutorial

Spread the love

JavaScript Fetch API Example: HTML, CSS & Vanilla JS Tutorial

Hey! If you have wanted to build a weather dashboard app using the JavaScript Fetch API but had no idea where to start, you are in the right place. Today, we are going to build something awesome together from scratch. Fetching real-time data from the web is a superpower for any web developer. Don’t worry if you are new to this; I will guide you through every single line of code.

By the end of this tutorial, you will have a sleek, working weather app on your screen. You can show it off to your friends and add it to your portfolio. Let’s dive right in and see what we are creating today!

What We Are Building with the JavaScript Fetch API

We are building a clean, modern weather dashboard that grabs live temperature and humidity stats. When you type in a city name, our app contacts a public weather service and displays the results instantly. This project is super useful because it teaches you how to talk to external servers and handle live data. It is very similar to building a Dynamic Data Dashboard: HTML, CSS, JavaScript Tutorial, but focused entirely on real-time weather stats!

Pro Tip: Bookmark this tutorial so you can come back to it whenever you need a quick refresher on asynchronous JavaScript!

HTML Structure

First, we need a simple HTML skeleton to hold our app elements like input fields and text cards. Here is the markup you need to set up the user interface.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Fetch API Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="app-container">
        <h1>JavaScript Fetch API</h1>
        <p class="subtitle">Click the button below to retrieve data asynchronously using vanilla JavaScript.</p>
        
        <div class="card">
            <button id="fetchBtn" class="btn">Fetch Random User</button>
            <div id="resultContainer" class="result-box">
                <span class="placeholder">Data will appear here...</span>
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS Styling

Next, we need to make our app look gorgeous with some modern CSS styling and a nice color palette. Here is the style sheet to give your dashboard a polished, professional look.

styles.css

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: Arial, Helvetica, sans-serif;
    background-color: #0f172a;
    color: #f8fafc;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    overflow: hidden;
}

.app-container {
    text-align: center;
    max-width: 500px;
    width: 100%;
    padding: 20px;
}

h1 {
    color: #38bdf8;
    font-size: 28px;
    margin-bottom: 8px;
}

.subtitle {
    color: #94a3b8;
    font-size: 14px;
    margin-bottom: 24px;
}

.card {
    background: rgba(30, 41, 59, 0.7);
    border: 1px solid rgba(56, 189, 248, 0.2);
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3);
}

.btn {
    background-color: #0284c7;
    color: #ffffff;
    border: none;
    border-radius: 6px;
    padding: 12px 20px;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
    width: 100%;
    transition: background-color 0.2s;
}

.btn:hover {
    background-color: #0369a1;
}

.result-box {
    margin-top: 20px;
    background-color: #090d16;
    border: 1px solid #1e293b;
    border-radius: 6px;
    padding: 16px;
    min-height: 100px;
    max-height: 200px;
    overflow-y: auto;
    text-align: left;
    font-family: monospace;
    font-size: 13px;
    color: #38bdf8;
}

.placeholder {
    color: #64748b;
    font-style: italic;
}

JavaScript and the JavaScript Fetch API

Now comes the fun part where we make the app actually work using the JavaScript Fetch API. Here is the script that listens for user input and grabs live weather data.

script.js

// Select DOM elements
const fetchBtn = document.getElementById('fetchBtn');
const resultContainer = document.getElementById('resultContainer');

// Add click event listener to trigger the fetch request
fetchBtn.addEventListener('click', async () => {
    // Show loading state
    resultContainer.innerHTML = '<span class="placeholder">Loading data...</span>';
    
    try {
        // Make the fetch request to a public API endpoint
        const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
        
        // Check if the network response was successful
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        
        // Parse the response body as JSON
        const data = await response.json();
        
        // Display the retrieved data nicely formatted
        resultContainer.innerHTML = `
            <strong>ID:</strong> ${data.id}<br>
            <strong>Name:</strong> ${data.name}<br>
            <strong>Email:</strong> ${data.email}<br>
            <strong>City:</strong> ${data.address.city}
        `;
    } catch (error) {
        // Handle any errors that occurred during the fetch
        resultContainer.innerHTML = `<span style="color: #ef4444;">Error: ${error.message}</span>`;
    }
});

How It All Works Together

Let me explain what is happening here under the hood so you can truly master the concepts. We use vanilla JavaScript to listen for clicks, grab input values, and make network requests.

Understanding the DOM Selection

First, we grab our HTML elements using query selectors. This lets us read what the user types into the search box and change the text on the screen later.

Making Network Requests

Here’s the cool part: we use the built-in fetch method to talk to our weather server. It sends an HTTP request across the internet and waits for a response without freezing the browser.

Handling JSON Responses

Once the server replies, we convert the raw data into a JavaScript object using the .json() method. Then, we easily pull out the temperature and city name to show them on our dashboard.

Tips to Customise It

Once you finish this basic app, you can level it up with some fun extra features. Here are three ideas to make your project stand out even more:

Encouragement: Don’t be afraid to break things while experimenting. That is literally the best way to learn how web development works!

Conclusion

You did it! You built a fully functional weather app from scratch using modern web tools. Take a moment to celebrate this awesome coding win. Share your new creation on Twitter or LinkedIn and tag procoder09. Keep coding, stay curious, and I will see you in the next tutorial!


Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *