Weather App using JavaScript, HTML, and CSS

In this tutorial, you'll learn to create a Weather App using JavaScript, HTML, and CSS. This application will fetch weather data from the OpenWeatherMap API based on user input and display it on the page.

Project Setup

Create a Project Directory: Name it weather-app. This will organize your project files.

File Structure:
  • index.html: Contains the markup for the application.
  • style.css: Styles the application.
  • script.js: Contains the logic to fetch and display weather data.

Development Steps

1. HTML Markup (index.html)

  • Start with a basic HTML structure. Link your CSS and JavaScript files.
  • Create a form with an input field for the user to search by location (e.g., city name).
  • Include a main element (<main>) where the weather data will be displayed.
Let's open the index.html file and add the following code to it:
<!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="style.css" />
        <script src="script.js" defer></script>
    </head>
    <body>
        <form id="form">
            <input
                type="text"
                id="search"
                placeholder="Search by location"
                autocomplete="off"
            />
        </form>
        <main id="main"></main>
    </body>
</html>

2. Styling (style.css) 

  • Apply global styles and import a font from Google Fonts for a clean look. 
  • Style the input field with rounded corners and a box shadow for depth. 
  • Design the weather display section to center content and enhance the visibility of weather information.
Let's open the style.css file and add the following CSS code to it:
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;600&display=swap");

* {
    box-sizing: border-box;
}

body {
    background: linear-gradient(300deg, #ced1d6, #bfc0c0);
    font-family: "Poppins", sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0;
    min-height: 100vh;
}

input {
    background-color: #fff;
    border: none;
    border-radius: 25px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
    font-family: inherit;
    font-size: 1rem;
    padding: 1rem;
    min-width: 300px;
}

input:focus {
    outline: none;
}

.weather {
    font-size: 2rem;
    text-align: center;
}

.weather h2 {
    display: flex;
    align-items: center;
    margin-bottom: 0;
}

3. JavaScript Logic (script.js)

Initialization: 

  • Define your API key from OpenWeatherMap
  • You’ll need to sign up for a free API key at OpenWeatherMap to use their service.
  • Select the DOM elements you will interact with: the form, search input, and main content area. 

Fetching Weather Data: 

  • Construct the API URL to fetch weather data for the user-specified location. 
  • Create an asynchronous function to fetch weather data using the Fetch API, then parse the response as JSON. 
  • Handle errors gracefully to alert the user if the data cannot be retrieved. 

Displaying Weather Data: 

  • Convert the temperature from Kelvin to Celsius for readability. 
  • Create a function to update the DOM with the weather data, including the temperature, weather conditions, and an icon representing the weather. 
  • Clear the previous search results each time new data is fetched. 

Event Handlers: 

  • Add an event listener to the form to prevent the default submit action and call the function to fetch and display weather data when a user searches for a location.
Let's open the script.js file and add the following JavaScript code to it:
const apikey = "3265874a2c77ae4a04bb96236a642d2f";

const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");

const url = (city) =>
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}`;

async function getWeatherByLocation(city) {
    const resp = await fetch(url(city), { origin: "cors" });
    const respData = await resp.json();

    console.log(respData);

    addWeatherToPage(respData);
}

function addWeatherToPage(data) {
    const temp = KtoC(data.main.temp);

    const weather = document.createElement("div");
    weather.classList.add("weather");

    weather.innerHTML = `
        <h2><img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /> ${temp}°C <img src="https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png" /></h2>
        <small>${data.weather[0].main}</small>
    `;

    // cleanup
    main.innerHTML = "";

    main.appendChild(weather);
}

function KtoC(K) {
    return Math.floor(K - 273.15);
}

form.addEventListener("submit", (e) => {
    e.preventDefault();

    const city = search.value;

    if (city) {
        getWeatherByLocation(city);
    }
});

Open index.html in Browser

Let's open the index.html file in the browser, and you will be able to see the following screen:
Weather App using JavaScript, HTML, and CSS

Conclusion 

Following these steps, you've created a functional Weather App that can provide real-time weather updates for different locations. This project introduces you to working with APIs, asynchronous JavaScript, and dynamically updating the HTML with JavaScript. 

Feel encouraged to expand on this project: 
  • Implement error handling for invalid location searches. 
  • Add more weather details like wind speed, humidity, and pressure. 
  • Explore adding a feature to switch between Celsius and Fahrenheit. 
  • Consider implementing a feature that uses the user's current location to fetch weather data automatically. 
This Weather App project serves as a practical introduction to creating web applications with JavaScript. It showcases the power of APIs in integrating dynamic data into projects.

Comments