Home » Modern Weather App with Live Forecast Using HTML & CSS and JavaScript

Modern Weather App with Live Forecast Using HTML & CSS and JavaScript

Weather App

Building a Weather App is a fantastic way to enhance your web development skills. In this tutorial, we’ll create a feature-rich weather application that fetches live weather data and forecasts using WeatherAPI. With a sleek design and user-friendly interface, this app demonstrates the power of HTML, CSS, and JavaScript.

Features of the Weather App:

  1. Live Weather Updates: Fetches current weather and forecast using WeatherAPI.
  2. Interactive UI: A search bar allows users to enter a location and view weather details instantly.
  3. Responsive Design: Uses Bootstrap for responsive layout and styling.
  4. 5-Day Forecast: Displays a visual summary of the upcoming weather.

Code Overview:

Below, you’ll find the complete code for the Weather App. Each part of the code is detailed for clarity.

HTML Structure:

The HTML provides the basic layout, including the input field for location, weather display, and forecast container.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>
    <div class="container d-flex justify-content-center align-items-center min-vh-100">
        <div class="weather-card text-center">
            <div class="mb-4">
                <input type="text" id="location-input" class="form-control search-bar" placeholder="Enter location (e.g., London)">
                <button id="search-button" class="btn btn-primary mt-3">Search</button>
            </div>
            <div id="weather-result">
                <h3 id="location-name"></h3>
                <img id="weather-icon" class="weather-icon" src="" alt="Weather Icon">
                <h1 id="temperature"></h1>
                <p id="weather-condition"></p>
            </div>
            <div id="forecast" class="forecast-container"></div>
        </div>
    </div>
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22https%3A%2F%2Fcdn.jsdelivr.net%2Fnpm%2Fbootstrap%405.3.0%2Fdist%2Fjs%2Fbootstrap.bundle.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />
</body>
</html>

CSS Styling:

The CSS ensures a modern and visually appealing design, with a focus on responsiveness and aesthetics.

   
        body {
            background-color: #6c63ff;
            color: #ffffff;
            font-family: Arial, sans-serif;
        }
        .weather-card {
            background: #ffffff;
            border-radius: 16px;
            padding: 20px;
            color: #333333;
            box-shadow: 0px 8px 20px rgba(0, 0, 0, 0.1);
        }
        .search-bar {
            border-radius: 50px;
            padding: 10px 20px;
            border: 1px solid #ccc;
        }
        .weather-icon {
            width: 80px;
            height: 80px;
        }
        .forecast-container {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }
        .forecast-item {
            text-align: center;
        }
    

 

JavaScript for Functionality:

The JavaScript integrates the WeatherAPI and dynamically updates the UI with weather data and forecasts.

    const apiKey = 'YOUR_API_KEY'; // Replace with your WeatherAPI key
    const searchButton = document.getElementById('search-button');
    const locationInput = document.getElementById('location-input');
    const locationName = document.getElementById('location-name');
    const weatherIcon = document.getElementById('weather-icon');
    const temperature = document.getElementById('temperature');
    const weatherCondition = document.getElementById('weather-condition');
    const forecastContainer = document.getElementById('forecast');

    searchButton.addEventListener('click', () => {
        const location = locationInput.value;
        if (!location) return alert('Please enter a location!');
        fetchWeather(location);
    });

    async function fetchWeather(location) {
        try {
            const response = await fetch(`https://api.weatherapi.com/v1/forecast.json?key=${apiKey}&q=${location}&days=5`);
            const data = await response.json();

            if (data.error) {
                alert(data.error.message);
                return;
            }

            updateWeatherUI(data);
        } catch (error) {
            console.error('Error fetching weather data:', error);
            alert('Failed to fetch weather data. Please try again.');
        }
    }

    function updateWeatherUI(data) {
        // Current weather
        locationName.textContent = `${data.location.name}, ${data.location.country}`;
        weatherIcon.src = `https:${data.current.condition.icon}`;
        temperature.textContent = `${data.current.temp_c}°C`;
        weatherCondition.textContent = data.current.condition.text;

        // Forecast
        forecastContainer.innerHTML = ''; // Clear previous forecast
        data.forecast.forecastday.forEach(day => {
            const forecastItem = document.createElement('div');
            forecastItem.className = 'forecast-item';
            forecastItem.innerHTML = `
                <p>${new Date(day.date).toLocaleDateString('en-GB', { weekday: 'short' })}</p>
                <img src="https:${day.day.condition.icon}" alt="Icon" width="40">
                <p>${day.day.avgtemp_c}°C</p>
            `;
            forecastContainer.appendChild(forecastItem);
        });
    }

How It Works:

  1. The user inputs a location in the search bar and clicks “Search.”
  2. The app fetches data from WeatherAPI using the location entered.
  3. Current weather details are displayed, including temperature, condition, and an icon.
  4. A 5-day forecast is dynamically generated and displayed below.

This Weather App showcases how to integrate a third-party API into a web project. By following this guide, you can create your own weather application, customize its appearance, or even expand its features to include hourly forecasts or alerts.