Open In App

Create a Weather Forecast Template using Tailwind CSS

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Weather Forecast Project enables the user to use real-time weather information for the city for which they have searched. We have used API which provides us with access to weather data from around the world. We have fetched the weather information for various locations, including wind speed, Humidity, Visibility, etc. The Interactive Weather Application is designed using Tailwind CSS.

Preview

23

CDN Link

<script src="https://cdn.tailwindcss.com"></script>

Approach

  • Create a basic HTML structure with an input field, a button to get weather information, and a container to display weather details.
  • Integrate Tailwind CSS into your project. You can either include it using CDN.
  • Use Tailwind CSS classes to style the input field, button, and weather information container for a clean and responsive design.
  • Write a JavaScript function (‘displayWeatherInfo’) that takes weather data as a parameter and dynamically creates HTML elements to display the information.
  • Inside the ‘displayWeatherInfo’ function, determine the temperature range and set the background image path accordingly.
  • Use JavaScript to set the `style.backgroundImage` property of the card element to the determined background image path.
  • Replace placeholder image paths with the actual paths or URLs to your dark snow/cloud and sunny background images.
  • Test the application by entering different cities with varying temperatures.

Example: Implementation to design the weather app using Tailwind CSS.

Javascript




const API_KEY = "be97c59d086b45bc695da756bae3e968";
const weatherInfo =
    document.getElementById('weatherInfo');
 
document.getElementById('getWeatherBtn')
    .addEventListener('click', function () {
        const cityInput = document.getElementById('cityInput').value;
        if (cityInput.trim() === '') {
            alert('Please enter a city name');
            return;
        }
 
        const units = 'metric';
 
        const URL =
`https://.../data/2.5/weather?q=${cityInput}&appid=${API_KEY}&units=${units}`;
 
        axios.get(URL)
            .then(response => {
                const data = response.data;
                displayWeatherInfo(data);
            })
            .catch(error => {
                console.error('Error fetching weather data:', error);
                weatherInfo.innerHTML =
                    '<p class="text-red-600">
                        Error fetching weather data. Please try again.
                     </p>';
            });
    });
 
function displayWeatherInfo(data) {
    const card = document.createElement('div');
    card.classList
        .add('bg-gray-800', 'text-white', 'p-6', 'rounded-md', 'shadow-md');
 
    // Set background image based on temperature
    let backgroundImage = '';
    if (data.main.temp < 8) {
        backgroundImage = 'url("2.jpg")';
    } else if (data.main.temp > 20) {
        backgroundImage = 'url("1.jpg")';
    }
 
    card.style.backgroundImage = backgroundImage;
 
    card.innerHTML = `
    <h2 class="text-2xl font-semibold mb-2">
        Location: ${data.name}, ${data.sys.country}
    </h2>
    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
      <div>
        <p class="text-lg">Temperature: ${data.main.temp}°C</p>
        <p class="text-lg">
            Weather: ${data.weather[0].description}
        </p>
      </div>
      <div>
        <p class="text-lg">
            Humidity: ${data.main.humidity}%
        </p>
        <p class="text-lg">
            Wind Speed: ${data.wind.speed} m/s
        </p>
        <p class="text-lg">
            Visibility: ${data.visibility / 1000} km
        </p>
      </div>
    </div>
  `;
 
    weatherInfo.innerHTML = '';
    weatherInfo.appendChild(card);
}


HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
          "width=device-width, initial-scale=1.0">
    <link rel="stylesheet"
          href="style.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <title>Weather App</title>
</head>
 
<body class="bg-gray-100 h-screen
             flex items-center justify-center">
    <div class="border-stone-600 container
                max-w-screen-sm
                mx-auto p-8 bg-white rounded-md
                shadow-md max-w-md">
        <h1 class="text-3xl text-center
                   font-bold text-green-600 mb-6">
            Weather App
        </h1>
        <div class="mb-4">
            <label for="cityInput"
                   class="block text-sm font-semibold mb-2">
                Enter Your City Name:
            </label>
            <input type="text" id="cityInput"
                   class="mt-1 p-3 border rounded-xl w-full
                       focus:outline-none focus:ring
                       focus:border-green-300"
                   placeholder="Jaisalmer">
        </div>
        <button id="getWeatherBtn"
                class="bg-green-600 text-white
                       p-3 mt-4 rounded-md
                       focus:ring focus:border-">
            Get Weather
        </button>
        <div id="weatherInfo"
             class="mt-6 text-gray-800"></div>
    </div>
 
    <script src=
      </script>
    <script src="script.js"></script>
</body>
 
</html>


CSS




body {
  font-family: 'Arial', sans-serif;
}


Output:

mnb'

Follow the Weather Forecast Project to make a web application with full documentation.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads