0%

How to Build a Weather Website Project Using HTML, CSS, and JavaScript

👋Welcome to Tutorial Temple

📢Introduction:

Are you interested in creating a weather website project that can display real-time weather updates? In this step-by-step guide, we will show you how to build a weather website using HTML, CSS, and JavaScript. This project is ideal for beginners and web developers looking to improve their skills while building a functional and attractive website.

▶️Weather Website Demo Video

Output Video

🤔💭What You Will Learn:

  • Project Setup: Learn how to organize your files and get your project ready.
  • HTML Structure: Understand the basic structure of your weather website.
  • CSS Styling: Discover how to style your website to make it look professional and responsive.
  • JavaScript Functionality: Learn how to fetch real-time weather data using an API and display it on your site.
  • Final Touches and Deployment: Optimize your website and deploy it online.
Tutorial Video

⚙️Step 1: Setting Up Your Weather Website Project

▶Before we start coding, you need to set up your project folder. Create a new folder on your computer called weather-website. Inside this folder, create the following files:

  • index.html (This will be your main HTML file)
  • styles.css (Your CSS file for styling)
  • script.js (Your JavaScript file for functionality)

⚡️To get weather data, sign up for a free API key from a weather service provider like
Weather Api

⚙️Step 2: Creating the HTML Structure

▶Open your index.html file and set up the basic HTML structure for your weather website:

<!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 rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">

</head>
<body>
    <div class="weather-container">
        <!-- Search container -->
        <div class="search-container">
            <input type="text" id="location" placeholder="Enter location">
            <button id="getWeather">Get Weather</button>
            
            
        </div>
        <div id="loader" class="loader" ></div>
        
        <!-- Weather Info Container -->
        <div class="weather-info">
            <!-- City Name, Time, and Country Code -->
            <div class="header">
                <h1 id="cityName"></h1>
                <p id="lastUpdate"></p>
            </div>

            <!-- Weather Icon -->
            <div class="weather-icon">
                <img id="weatherIcon" alt="Weather Icon">
            </div>

            <!-- Temperature and Condition -->
            <div class="temperature-condition">
                <p id="temperature"></p>
                <p id="condition"></p>
            </div>

            <!-- Weather Details Grid -->
            <div class="weather-grid">
                <div class="weather-data">
                    <p id="humidity"></p>
                    <p id="windSpeed"></p>
                    <p id="gustwind"></p>
                    <p id="windDirection"></p>
                    <p id="pressure"></p>
                </div>
                <div class="weather-data">
                    <p id="feelsLike"></p>
                    <p id="windchill"></p>
                    <p id="precipitation"></p>
                    <p id="uvIndex"></p>
                    <p id="visible"></p>
                </div>
            </div>
        </div>
        <p id="localTime2"></p>

        <div class="forecast-info">
            <h2><i class="fa-solid fa-calendar-days"></i> 7-Days Forecast</h2>
            <div id="forecastContainer"></div>
        </div>

        <div class="alerts-info">
            <h2><i class="fa-solid fa-circle-exclamation"></i> Weather Alerts</h2>
            <div id="alertsContainer"></div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="script.js"></script>
</body>
</html>

▶This HTML structure includes a search box for users to input a city name, and an area where weather information will be displayed and also forcast detals and weather alerts will show. It’s simple but effective, making it easy to style and add functionality.

⚙️Step 3: Styling with CSS

▶Open yourstyles.cssfile and add the following CSS to style your weather website:

▶In your ‘weather-website’ file put this gif file (make sure this file name should be ‘w2.gif’):

📥Download Your gif File
/* General styles */
:root
{
--body: #cefcff;
--button: #00b62d;
--button-hover: #0056b3;
--city-name: #00b62d;
--item-box: #ffffff5d;
--section: #ffffff2d;
--forcast-day: #f0ff172d;
--hour-container: #f7f7f757;
--hour-card: #ffffff13;

}
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    margin: 0;
    padding: 0;
    background-color: var(--body);
    color: #333;
}

.weather-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 10px;
    background: #ffffff00;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    gap: 20px;
}
.weather-container p2{
    margin-top: 0px;
    text-align: center;
    border: 1px solid rgb(22, 115, 255);
    border-radius: 8px;
    
}
/* Search container */
.search-container {
    position: relative; /* Position relative to align autocomplete */
    display: flex; /* Align input and button horizontally */
    justify-content: center; /* Center input and button horizontally */
}

.search-container input {
    flex: 1; /* Allows the input to take up remaining space */
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
    max-width: 500px;
}

#getWeather {
    padding: 10px;
    cursor: pointer;
    background-color: var(--button);
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    width: 120px; /* Adjust width as needed */
    transition: background-color 0.3s ease;
}

#getWeather:hover {
    background-color: var(--button-hover);
}

/* Weather Info Section */
.weather-info {
    background-image: url('w2.gif');
    opacity: 1;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;  
    background-color: #ffffff04;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    text-align: center;
    display: none;
    margin-bottom: -50px;
}

.weather-info h1 {
    margin: 0;
    font-size: 25px;
    color: var(--city-name);
}
.weather-info p1{
    margin-top: 0px;
    font-size: 20px;
    color: #00a2ff;
}
.weather-info p {
    margin: 5px 0;
    font-size: 12px;
}

.weather-icon img {
    max-width: 100px;
}

.temperature-condition p {
    margin: 5px 0;
    font-size: 18px;
}

/* Grid layout for weather details */
.weather-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    text-align: center;
    
}

.weather-data {
    background: #ffffff9c;
    padding: 5px;
    border-radius: 4px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    border: 1px solid #ddd;
}
.item {
    background: var(--item-box);
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 10px;
    text-align: center;
    font-size: 15px;
}
.weather-data p {
    margin: 0;
    font-size: 14px;
}

/* Responsive design for weather grid */
@media screen and (max-width: 600px) {
    .weather-info
    {
        padding: 10px;
    }
    .weather-grid {
        grid-template-columns: repeat(2, 1fr); /* Two columns for mobile */
    }
    .weather-data {
        font-size: 14px; /* Smaller font size for mobile */
    }
}

/* Forecast and Alerts Section */
.forecast-info, .alerts-info {
    background: var(--section);
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    animation: fadeIn 0.5s ease-in-out;
    display: none;
}

.forecast-info h2, .alerts-info h2 {
    margin-top: 0;
    color: #333;
    text-align: center;
}

.forecast-day {
    margin-bottom: 30px;
    overflow: hidden;
    text-align: left;
    justify-content: center;
    transition: max-height 0.5s ease-out;
}

.forecast-day .day {
    overflow: hidden;
    text-align: center;
    transition: max-height 0.5s ease-out;
    font-weight: bold;
    font-size: 20px;
    border: 1px solid #eb6a00; /* 2px solid black border */
    background: var(--forcast-day);
    text-transform: capitalize;
    padding: 10px;
    border-radius: 5px;
}

.forecast-day.expanded {
    max-height: 500px; /* Adjust based on content */
}

.forecast-day img {
    width: 60px;
    height: auto;
}

/* Hourly Forecast */
.hourly-scroll-container {
    overflow-x: auto;
    white-space: nowrap;
    padding: 10px 0;
    margin-top: 0;
    border-radius: 8px;
    background: var(--hour-container);
    border: 1px solid #ddd;
}

.hourly-day {
    display: flex;
    align-items: center;
    gap: 10px;
}

.hourly-card {
    display: inline-block;
    vertical-align: top;
    width: wrap; /* Adjust width as needed */
    background: var(--hour-card);
    border-radius: 8px;
    margin-left: 5px;
    margin-right: -4px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    text-align: center;
    padding: 10px;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hourly-card:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.hourly-card .hour-time {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 5px;
}

.hourly-card .temperature {
    font-size: 14px;
    margin-bottom: 5px;
}

.hourly-card .condition {
    font-size: 12px;
    margin-bottom: 5px;
}

.hourly-card .precipitation, .hourly-card .wind-direction {
    font-size: 12px;
    color: #666;
}

/* Autocomplete Container */
.autocomplete-container {
    position: absolute;
    z-index: 1000;
    max-height: 200px;
    overflow-y: auto;
    background-color: white;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    display: none; /* Hidden by default */
}

.autocomplete-item {
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #ddd;
}

.autocomplete-item:hover {
    background-color: #f0f0f0;
}
.loader {
    display: inline-block;
    width: 40px;
    height: 40px;
    margin-left: 45%;
    margin-top: 5px;
    border: 8px solid rgba(0, 0, 0, 0.1);
    border-radius: 50%;
    border-top-color: #00c921;
    animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

▶This CSS code makes your weather website look clean and modern. The container is centered on the page, and the search box and weather information are styled to be user-friendly and visually appealing.

⚙️Step 4: Fetching Weather Data with JavaScript

▶Next, let’s add the functionality to fetch and display weather data. Open your script.jsfile and add the following code:

document.addEventListener('DOMContentLoaded', () => {
    const apiKey = '#'; // Replace with your API key
    const currentWeatherUrl = 'https://api.weatherapi.com/v1/current.json';
    const forecastUrl = 'https://api.weatherapi.com/v1/forecast.json';
    const searchUrl = 'https://api.weatherapi.com/v1/search.json'; // Your search endpoint
    

    const locationInput = document.getElementById('location');
    const autocompleteContainer = document.createElement('div');
    autocompleteContainer.className = 'autocomplete-container';
    locationInput.parentNode.appendChild(autocompleteContainer);
    

    locationInput.addEventListener('input', () => {
        const query = locationInput.value.trim();
        if (query) {
            fetch(`${searchUrl}?key=${apiKey}&q=${query}`)
                .then(response => response.json())
                .then(data => {
                    autocompleteContainer.innerHTML = '';
                    data.forEach(result => {
                        const suggestion = document.createElement('div');
                        suggestion.className = 'autocomplete-item';
                        suggestion.innerHTML = `${result.name}, ${result.country}`;
                        suggestion.addEventListener('click', () => {
                            locationInput.value = `${result.name}, ${result.country}`;
                            autocompleteContainer.innerHTML = '';
                            autocompleteContainer.style.display = 'none'; // Hide after selection
                            fetchWeatherData(result.name);
                        });
                        autocompleteContainer.appendChild(suggestion);
                    });

                    // Position the container below the input field
                    const inputRect = locationInput.getBoundingClientRect();
                    autocompleteContainer.style.top = `${inputRect.bottom + window.scrollY}px`;
                    autocompleteContainer.style.left = `${inputRect.left + window.scrollX}px`;
                    autocompleteContainer.style.width = `${inputRect.width}px`; // Align width with the input field
                    autocompleteContainer.style.display = 'block'; // Show the dropdown
                })
                .catch(error => {
                    console.error('Error fetching autocomplete data:', error);
                });
        } else {
            autocompleteContainer.innerHTML = '';
            autocompleteContainer.style.display = 'none'; // Hide the dropdown
        }
    });

    document.getElementById('getWeather').addEventListener('click', () => {
        const location = locationInput.value.trim();
        if (location) {
            autocompleteContainer.innerHTML = ''; // Clear any suggestions
            autocompleteContainer.style.display = 'none'; // Hide the suggestion container
            fetchWeatherData(location);
        } else {
            Swal.fire({
                icon: 'warning',
                title: 'Oops...!',
                text: 'Please enter a location.',
            });
        }
    });

    async function fetchWeatherData(location) {
        try {
            // Fetch current weather
            const weatherResponse = await fetch(`${currentWeatherUrl}?key=${apiKey}&q=${location}`);
            const weatherData = await weatherResponse.json();
            displayCurrentWeather(weatherData);
            document.getElementById('loader').style.display = 'inline-block';

            // Fetch 7-day forecast
            const forecastResponse = await fetch(`${forecastUrl}?key=${apiKey}&q=${location}&days=7`);
            const forecastData = await forecastResponse.json();
            displayForecast(forecastData);
            
            // Fetch weather alerts
            const alertsFetchUrl = `${forecastUrl}?key=${apiKey}&q=${location}&days=7&alerts=yes`;
            console.log('Fetching alerts from URL:', alertsFetchUrl); // Log the URL being called
            const alertsResponse = await fetch(alertsFetchUrl);
            const alertsData = await alertsResponse.json();
            displayAlerts(alertsData);
            

            Swal.fire({
                toast: true,
                position: 'top-right',
                icon: 'success',
                title: 'Weather Data Loaded',
                text: 'Weather data has been successfully fetched.',
                timer: 3000,
                showConfirmButton: false
            });

        } catch (error) {
            console.error('Error fetching weather data:', error);
            Swal.fire({
                toast: true,
                position: 'top-right',
                icon: 'error',
                title: 'Error',
                text: 'Error fetching weather data. Please try again.',
                timer: 3000,
                showConfirmButton: false
            });
        }finally {
            // Hide the loader
            document.getElementById('loader').style.display = 'none';
        }
    }

    function displayCurrentWeather(data) {
        if (data.error) {
            Swal.fire({
                toast: true,
                position: 'top-right',
                icon: 'error',
                title: 'Error',
                text: `Error: ${data.error.message}`,
                timer: 3000,
                showConfirmButton: false
            });
            return;
        }
    
        const placeName = data.location.name;
        const country = data.location.country;
        const region = data.location.region; // This is usually the state or province
        const localTime = new Date(data.location.localtime);
        const timeZone = data.location.tz_id; // Time zone ID
    
        // Format the time with time zone
        const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit'  };
        const formattedTime = localTime.toLocaleString('en-US', options);
        const lastUpdated = new Date(data.current.last_updated);
        const formattedLastUpdated = lastUpdated.toLocaleString('en-US', { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        
        // Update HTML with the desired format
        document.getElementById('cityName').innerHTML = `<h2><i class="fa-solid fa-location-dot"></i> ${placeName}</h2><p1>(${country}, ${region}, ${formattedTime})</p1>`;
        document.getElementById('lastUpdate').innerHTML = `<p><i class="fa-solid fa-arrows-rotate"></i> Last Update: ${formattedLastUpdated}</p>`;

        // Rest of your code to display weather data
        document.getElementById('temperature').innerHTML = `<i class="fas fa-temperature-high"></i> ${data.current.temp_c}°C`;
        document.getElementById('condition').innerHTML = `<i class="fas fa-cloud-sun"></i> ${data.current.condition.text}`;
        document.getElementById('humidity').innerHTML = `<i class="fas fa-tint"></i> Humidity: ${data.current.humidity}%`;
        document.getElementById('windSpeed').innerHTML = `<i class="fas fa-wind"></i> Wind Speed: ${data.current.wind_kph}km/h`;
        document.getElementById('windchill').innerHTML = `<i class="fa-solid fa-water"></i> Wind Chill: ${data.current.windchill_c}°C`;
        document.getElementById('gustwind').innerHTML = `<i class="fas fa-wind"></i> Gust Wind: ${data.current.gust_kph}km/h`;
        document.getElementById('windDirection').innerHTML = `<i class="fa-solid fa-compass"></i> Wind Direction: ${data.current.wind_dir}`;
        document.getElementById('feelsLike').innerHTML = `<i class="fas fa-thermometer-half"></i> Feels Like: ${data.current.feelslike_c}°C`;
        document.getElementById('pressure').innerHTML = `<i class="fas fa-tachometer-alt"></i> Pressure: ${data.current.pressure_mb} mb`;
        document.getElementById('visible').innerHTML = `<i class="fa-solid fa-eye"></i> Visibility: ${data.current.vis_km} km`;
        document.getElementById('uvIndex').innerHTML = `<i class="fas fa-sun"></i> UV Index: ${data.current.uv}`;
        document.getElementById('precipitation').innerHTML = `<i class="fa-solid fa-cloud-rain"></i> Precipitation: ${data.current.precip_mm} mm`;
        document.getElementById('weatherIcon').src = `http:${data.current.condition.icon}`;
        document.querySelector('.weather-info').style.display = 'block';
    }
    

    function displayForecast(data) {
        if (data.error) {
            alert(`Error: ${data.error.message}`);
            return;
        }

        const forecastContainer = document.getElementById('forecastContainer');
        forecastContainer.innerHTML = '';

        data.forecast.forecastday.forEach(day => {
            const date = new Date(day.date);
            const dayName = date.toLocaleDateString('en-US', { weekday: 'long' });
            const temperature = `<i class="fas fa-temperature-high"></i> ${day.day.avgtemp_c}°C`;
            const condition = day.day.condition.text;
            const weatherIcon = day.day.condition.icon;
            const precipitation = `<i class="fa-solid fa-cloud-rain"></i> Precipitation: ${day.day.totalprecip_mm} mm`;
            const windSpeed = `<i class="fas fa-wind"></i> Wind Speed: ${day.day.maxwind_kph} km/h`;
            const uvIndex = `<i class="fas fa-sun"></i> UV Index: ${day.day.uv}`;
            const humidity = `<i class="fas fa-tint"></i> Humidity: ${day.day.avghumidity}%`;
            const visible = `<i class="fa-solid fa-eye"></i> Visibility: ${day.day.avgvis_km}km`;
            const sunrise = `<i class="fas fa-sun"></i> Sunrise: ${day.astro.sunrise}`;
            const sunset = `<i class="fa-solid fa-cloud-sun"></i> Sunset: ${day.astro.sunset}`;
            const moonrise = `<i class="fas fa-moon"></i> Moonrise: ${day.astro.moonrise}`;
            const moonset = `<i class="fa-solid fa-cloud-moon"></i> Moonset: ${day.astro.moonset}`;
            const moonPhase = `<i class="fas fa-moon"></i> Moon Phase: ${day.astro.moon_phase}`;
            const mintemp = `<i class="fa-solid fa-temperature-empty"></i> Min. Temp.: ${day.day.mintemp_c}°C`;
            const rain = `<i class="fa-solid fa-umbrella"></i> Rain Chance: ${day.day.daily_chance_of_rain}%`;

           const forecastDay = document.createElement('div');
            forecastDay.className = 'forecast-day';
            forecastDay.innerHTML = `
               <div class="weather-container">
                    <div class="day"><i class="fa-regular fa-calendar-check"></i> ${dayName}</div>
                    <div class="weather-grid">
                        <div class="item top-left">
                            <img src="http:${weatherIcon}" alt="${condition}" />
                            <div>${temperature}</div>
                            <div>${condition}</div>
                        </div>
                        <div class="item top-right">
                            <div>${precipitation}</div>
                            <div>${rain}</div>
                            <div>${visible}</div>
                            <div>${windSpeed}</div>
                             <div>${humidity}</div>
                            
                        </div>
                        <div class="item bottom-left">
                           <div>${mintemp}</div>
                           <div>${uvIndex}</div>
                           <div>${sunrise}</div>
                            <div>${sunset}</div>
                        </div>
                        <div class="item bottom-right">
                            <div>${visible}</div>
                            <div>${moonrise}</div>
                            <div>${moonset}</div>
                            <div>${moonPhase}</div>
                        </div>
                    </div>
                    <p2>Hourly Weather</p2>
                    <div class="hourly-scroll-container" data-date="${day.date}">
                    <div class="hourly-day" id="hourly-${day.date}"></div>
                </div>
                </div>

                
            `;
            forecastContainer.appendChild(forecastDay);

            // Fetch hourly data for the day
            fetch(`${forecastUrl}?key=${apiKey}&q=${location}&dt=${day.date}`)
                .then(response => response.json())
                .then(dayData => {
                    const hourlyData = dayData.forecast.forecastday[0].hour;
                    const hourlyDayContainer = document.getElementById(`hourly-${day.date}`);
                    hourlyDayContainer.innerHTML = '';

                    hourlyData.forEach(hour => {
                        const time = new Date(hour.time_epoch * 1000).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
                        const temp = `${hour.temp_c}°C`;
                        const condition = hour.condition.text;
                        const weatherIcon = hour.condition.icon;
                        const precipitation = `<i class="fa-solid fa-cloud-rain"></i> Precipitation: ${hour.precip_mm} mm`;
                        const windSpeed = `<i class="fas fa-wind"></i> Wind Speed: ${hour.wind_kph} km/h`;
                        const windDirection = `<i class="fas fa-compass"></i> Wind Direction: ${hour.wind_dir}`;
                        const uvIndex = `<i class="fas fa-sun"></i> UV Index: ${hour.uv}`;
                        const humidity = `<i class="fas fa-tint"></i> Humidity: ${hour.humidity}%`;

                        const hourCard = document.createElement('div');
                        hourCard.className = 'hourly-card';
                        hourCard.innerHTML = `
                            <img src="http:${weatherIcon}" alt="${condition}" />
                            <div class="hour-time"><i class="fa-solid fa-clock"></i> ${time}</div>
                            <div><i class="fa-solid fa-temperature-high"></i> ${temp}</div>
                            <div><i class="fa-solid fa-smog"></i> ${condition}</div>
                            <div>${precipitation}</div>
                            <div class="wind-speed">${windSpeed}</div>
                            <div>${windDirection}</div>
                            <div class="uv-index">${uvIndex}</div>
                            <div class="humidity">${humidity}</div>
                        `;
                        hourlyDayContainer.appendChild(hourCard);
                    });
                })
                .catch(error => {
                    console.error('Error fetching hourly data:', error);
                    alert('Error fetching hourly data. Please try again.');
                });
        });

        document.querySelector('.forecast-info').style.display = 'block';
    }

    async function displayAlerts(data) {
        console.log('API Response:', data); // Log the API response for debugging
    
        // Function to show SweetAlert as a toast after a delay
        function showToastWithDelay(icon, title, text) {
            return new Promise(resolve => {
                setTimeout(() => {
                    Swal.fire({
                        icon: icon,
                        title: title,
                        text: text,
                        toast: true, // Show as a toast
                        position: 'top-end', // Position of the toast
                        showConfirmButton: false, // Hide confirm button
                        timer: 7000, // Auto-hide after 3 seconds
                        timerProgressBar: true,
                        showCloseButton: true
                    });
                    resolve();
                }, 5000); // 5 seconds delay
            });
        }
    
        const alertsContainer = document.getElementById('alertsContainer');
    
        // Check if alerts exist and are in the expected format
        if (data.alerts && data.alerts.alert && Array.isArray(data.alerts.alert) && data.alerts.alert.length > 0) {
            alertsContainer.innerHTML = '';
    
            // Loop through each alert and display it in the container
            data.alerts.alert.forEach(alert => {
                const alertDiv = document.createElement('div');
                alertDiv.className = 'alert';
                alertDiv.innerHTML = `
                    <div><strong>${alert.event}</strong></div>
                    <div>${alert.desc}</div>
                    <div>${alert.instruction || 'No instructions available'}</div>
                    <div>Expires: ${alert.expires}</div>
                `;
                alertsContainer.appendChild(alertDiv);
            });
    
            document.querySelector('.alerts-info').style.display = 'block';
    
            // Show a SweetAlert toast for the alert after 5 seconds
            await showToastWithDelay(
                'warning',
                'Weather Alert',
                `Alert: ${data.alerts.alert.map(alert => alert.event).join(', ')}`
            );
    
        } else {
            // Show a safe zone toast if no alerts are available after 5 seconds
            await showToastWithDelay(
                'info',
                'Safe Zone',
                'No weather alerts available at the moment.'
                
            );
    
            // Show the default message in the alerts container
            alertsContainer.innerHTML = '<p>No alerts available.</p>';
            document.querySelector('.alerts-info').style.display = 'block'; // Show the container even if empty
        }
    }
    

    // Get user's geolocation and fetch weather data based on it
    
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            const lat = position.coords.latitude;
            const lon = position.coords.longitude;
            fetchWeatherData(`${lat},${lon}`);
        }, error => {
            Swal.fire({
                toast: true,
                position: 'top-right',
                icon: 'error',
                title: 'Geolocation Error',
                text: 'Unable to fetch your location.',
                timer: 3000,
                showConfirmButton: false
            });
        });
    } else {
        Swal.fire({
            toast: true,
            position: 'top-right',
            icon: 'warning',
            title: 'Geolocation Not Supported',
            text: 'Your browser does not support geolocation.',
            timer: 3000,
            showConfirmButton: false
        });
    }
});

▶This JavaScript code fetches weather data from the WeatherApi API based on the city name entered by the user and displays it on the webpage. The code includes error handling to alert the user if the city is not found.

⚙️Step 5: Final Touches and Deployment

▶Before deploying your weather website, ensure it’s responsive and optimized for performance. You can use tools like Google PageSpeed Insights to test your website’s performance and make improvements.

⚡️Once you’re satisfied with your project, deploy it using a free hosting service like GitHub Pages, Netlify, or Vercel.

🎯Conclusion:

Building a weather website project using HTML, CSS, and JavaScript is a fantastic way to practice web development skills while creating a useful tool. This guide provides a straightforward approach to creating a responsive and functional weather website. Whether you’re a beginner or an experienced developer, this project is sure to enhance your portfolio.

📌Call to Action:

Did you find this guide helpful? Share it with others, and don’t hesitate to leave a comment if you have any questions or need further assistance!

Expert WordPress developer specializing in creating engaging, SEO-friendly, and responsive blogging websites.

Share this content:

Leave a Comment