Creating a Simple Weather App: A Step-by-Step Guide with HTML, CSS, and JavaScript

Creating a Simple Weather App: A Step-by-Step Guide with HTML, CSS, and JavaScript

In a tech world dominated by frameworks and libraries, it's essential to grasp the inner workings of web development. Today, we're going to create a straightforward weather app using only HTML, CSS, and JavaScript. We'll also use a free weather API – in this case, I've chosen the one provided by https://www.weatherapi.com, but you're free to pick any other API that suits your needs.

Let's kick things off by crafting an HTML file with a standard boilerplate code. We'll then create a basic card structure featuring an H1 tag with "Weather App" and some data points. To keep things simple, we'll start with hard-coded values to get the app up and running.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Weather App">
    <title>Weather App</title>
</head>
<body>
    <div class="container">
        <h1>Weather App</h1>
        <div class="card-container">
            <div class="search">
                <input type="text" class="input-text" placeholder="Enter text">
                <button id="myBtn">Search</button>
            </div>
            <div class="name-temp">
                <div class="cityName">City Name: --</div>
                <div class="temp">Temp: --</div>
            </div>
            <div class="humidity">
                Humidity: --
            </div>
            <div class="wind-speed">
                Wind Speed: --
            </div>
            <div class="LocalSpeed">
                Local Time: --
            </div>
        </div>
    </div>
</body>
</html>

Simple stucture with html

Now that we've set the stage for our weather app using HTML, it's time to add a touch of beauty to the interface. While I'll make some basic changes, you have the creative power to design the card and give it your unique flair.

create and link files to the HTML.

<link rel="stylesheet" href="style.css">
.card-container {
  width: 300px;
  margin: 0 auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.2);
  background-color: #fff;
}

.search {
  display: flex;
  align-items: center;
  padding: 10px;
}

.search input {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
}

.search button {
  background-color: #000;
  color: #fff;
  border: none;
  border-radius: 5px;
  padding: 5px;
  margin-left: 10px;
}

.name-temp {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}

.cityName {
  font-size: 20px;
  font-weight: bold;
}

.temp {
  font-size: 16px;
}

.humidity,
.wind-speed {
  padding: 10px;
}

.humidity,
.wind-speed span {
  color: #999;
}

.wind-speed {
  padding-bottom: 10px;
}

.LocalSpeed {
  padding: 10px;
}

card design after adding styles

"Unleashing the Magic: Adding JavaScript to our Weather App"

The real enchantment begins now as we introduce JavaScript to our HTML file. However, we'll do so with a twist to ensure the smooth execution of our code. We'll use the <script> tag with the 'defer' attribute to ensure that JavaScript runs after the HTML content has loaded. Stay tuned because I'll be writing a blog soon explaining the difference between 'defer' and 'async' – important concepts for web development.

With JavaScript, we'll make our weather app come to life, providing real-time data and interactivity. So, let's proceed and see the magic unfold!

    <script src="index.js" defer></script>
// Function to fetch weather data
const fetchWeather = async (cityName) => {
    const API_KEY = 
    const apiUrl = `http://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${cityName}&aqi=no`;
    const response = await fetch(apiUrl);
    const data = await response.json();

    if (data && data.location && data.current) {
        let cityName = data.location.name;
        let temperature = data.current.temp_c;
        let humidity = data.current.humidity;
        let windSpeed = data.current.wind_kph;
        let localTime = data.location.localtime;

        document.querySelector(".cityName").innerHTML = "City Name: " + cityName;
        document.querySelector(".temp").innerHTML = "Temp: " + temperature + "°C";
        document.querySelector(".humidity").innerHTML = "Humidity: " + humidity + "%";
        document.querySelector(".wind-speed").innerHTML = "Wind Speed: " + windSpeed + " Km/h";
        document.querySelector(".LocalSpeed").innerHTML = "Local Time: " + localTime;
    }
};

document.addEventListener("DOMContentLoaded", function () {

    const inputText = document.querySelector(".input-text");
    const searchBtn = document.getElementById("myBtn");

    searchBtn.addEventListener("click", () => {
        const cityName = inputText.value;
        fetchWeather(cityName);
    });
});

Certainly, let's break down the code you've provided step by step:

  1. const fetchWeather = async (cityName) => { ... }:

    • This code defines an asynchronous function named fetchWeather that takes a cityName as a parameter. This function will fetch weather data for the specified city.
  2. const API_KEY = ...:

    • This is where you should define your Weather API key. You'd replace ... with your actual API key from the Weather API service.
  3. const apiUrl = ...:

    • This constructs the URL for making the API request. It includes the API key and the city name. The API endpoint for fetching weather data is from "http://api.weatherapi.com."
  4. const response = await fetch(apiUrl);:

    • This line makes an HTTP request to the URL constructed earlier using the fetch function. The await keyword is used to pause execution until the promise returned by fetch resolves.
  5. const data = await response.json();:

    • After receiving the response from the API, this line extracts and parses the JSON data. Again, await is used to wait for the response to be processed.
  6. if (data && data.location && data.current) { ... }:

    • This condition checks if the data received from the API is valid and contains the necessary information. It ensures that location and current data objects exist.
  7. The following lines extract data from the API response:

    • cityName, temperature, humidity, windSpeed, and localTime are assigned values from the data object.
  8. The next set of lines updates the HTML content to display the retrieved weather data. It uses document.querySelector to select specific elements in the HTML document and sets their innerHTML property with the corresponding weather information.

  9. The code waits for the DOMContentLoaded event to ensure that the JavaScript is executed after the HTML document is fully loaded. This is crucial to ensure that HTML elements you're trying to interact with exist at the time the JavaScript code runs.

  10. const inputText = document.querySelector(".input-text");:

    • This line selects an HTML element with the class "input-text," which is presumably an input field where the user can type in a city name.
  11. const searchBtn = document.getElementById("myBtn");:

    • This line selects an HTML element with the id "myBtn," which is presumably a button element.
  12. searchBtn.addEventListener("click", () => { ... }:

    • This code adds a click event listener to the "myBtn" button. When the button is clicked, the provided function is executed.
  13. const cityName = inputText.value;:

    • This line retrieves the value entered by the user in the input field (presumably the city name) and assigns it to the cityName variable.
  14. fetchWeather(cityName);:

    • This line calls the fetchWeather function with the cityName as an argument when the button is clicked. It initiates the process of fetching and displaying weather data for the specified city.

In summary, this code defines a function to fetch weather data from an API, listens for a button click event, and initiates the API request when the button is clicked. It then updates the HTML content with the retrieved weather information.

In this blog, we've taken a step-by-step journey into creating a weather app from the ground up using HTML, CSS, and JavaScript. We've learned how to make an asynchronous API request, process the data it returns, and display it in our web interface. With this fundamental understanding, you're well on your way to exploring more complex web applications and gaining a deeper insight into web development. So, whether you're just starting out on your coding adventure or looking to expand your knowledge, remember that understanding the core principles empowers you to create and innovate in the ever-evolving world of web development. Keep coding, keep learning, and watch your projects come to life!