Building a Simple Weather Dashboard with JavaScript and Mock APIs
Published: 2024-06-02 17:53:41

Creating a weather dashboard is a great way to practice working with APIs and building user interfaces. In this tutorial, we'll build a simple weather dashboard using JavaScript and a Mock Weather API. This will allow us to fetch and display weather data without needing access to a live weather API. The [Mock API](https://mockx.net) will simulate real-world scenarios, making it an excellent tool for development and testing.
We will be using [Dummy Weather API ](https://mockx.net/docs/weather-api)for this project.
Prerequisites
To follow along with this tutorial, you'll need:

- Basic knowledge of HTML, CSS, and JavaScript.
- A code editor (like VSCode).
- A web browser.

## Setting Up the Project

First, let's set up a simple HTML page that will serve as our weather dashboard.


```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather Dashboard</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        .weather {
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 5px;
            margin-top: 20px;
            width: 300px;
            text-align: center;
        }
    </style>
</head>
<body>
    <h1>Weather Dashboard</h1>
    <input type="text" id="city" placeholder="Enter city name">
    <button id="getWeather">Get Weather</button>
    <div id="weatherContainer"></div>

    <script src="app.js"></script>
</body>
</html>
```

## Writing JavaScript to Fetch Weather Data
Next, we'll write JavaScript to fetch weather data from the Mock API and display it on our dashboard.

Create a file named app.js and add the following code:

```
document.getElementById('getWeather').addEventListener('click', getWeather);

async function getWeather() {
    const city = document.getElementById('city').value;
    if (!city) {
        alert('Please enter a city name');
        return;
    }

    try {
        const response = await fetch(`https://api.mockx.net/weather/search?q=${city}`);
        const data = await response.json();
        displayWeather(data.weathers);
    } catch (error) {
        console.error('Error fetching weather data:', error);
    }
}

function displayWeather(weathers) {
    const weatherContainer = document.getElementById('weatherContainer');
    weatherContainer.innerHTML = ''; // Clear previous weather data

    if (weathers.length === 0) {
        weatherContainer.innerHTML = '<p>No weather data found for the entered city.</p>';
        return;
    }

    weathers.forEach(weather => {
        const weatherDiv = document.createElement('div');
        weatherDiv.className = 'weather';
        weatherDiv.innerHTML = `
            <h2>${weather.location.city}, ${weather.location.country}</h2>
            <p>Temperature: ${weather.current_weather.temperature}°C</p>
            <p>Condition: ${weather.current_weather.weather_condition}</p>
            <p>Humidity: ${weather.current_weather.humidity}%</p>
            <p>Wind Speed: ${weather.current_weather.wind_speed} km/h</p>
            <p>Air Quality: ${weather.air_quality.category} (${weather.air_quality.index})</p>
        `;
        weatherContainer.appendChild(weatherDiv);
    });
}
```

## Explanation
HTML Structure: We have a simple HTML structure with an input field for the city name, a button to trigger the weather fetch, and a container to display the weather data.

Fetching Weather Data: When the button is clicked, the getWeather function is called. This function fetches weather data from the Mock API based on the entered city name.

Displaying Weather Data: The displayWeather function takes the fetched weather data and dynamically creates HTML elements to display the information.

## Running the Application
To run the application, simply open the index.html file in your web browser. Enter a city name and click the "Get Weather" button to see the weather data for that city.

## Conclusion
Using Mock APIs is a fantastic way to practice working with real-world data without needing access to live servers. In this tutorial, we built a simple weather dashboard using JavaScript and a Mock Weather API. This approach allows you to test and develop your applications in a controlled environment.

For more information on Mock APIs, you can check out [MockX](https://mockx.net).