Weather App Using HTML CSS and JavaScript

0

hey everyone hope you are all fine, today we are going to learn how to make weather app using HTML CSS and JavaScript from scratch with a cool design. It’s a great project for improving your HTML CSS and JS skills also you can add that to your portfolio. Basically, It’s an API-based project, inside the project you will learn how to use API to display the data inside your website or application.

Weather App Using HTML CSS and JavaScript

In today’s fast-paced world, staying up to date with the weather is essential for planning our daily activities. Whether you’re planning a weekend getaway, deciding what to wear, or preparing for an outdoor event, having easy access to accurate weather information is crucial. This article will explore how to create a dynamic weather app using HTML CSS and JavaScript. This project will not only serve as a practical tool but also provide valuable insights into web development.

Why Build a Weather App?

Before diving into the technical aspects, let’s understand why building a weather app can be a rewarding project. Here are a few reasons why creating your weather app can be both fun and educational:

  1. Hands-on Learning: Developing a weather app allows you to apply your knowledge of HTML, CSS, and JavaScript in a practical context. It’s an excellent way to reinforce your coding skills.
  2. Real-world Application: Weather apps are widely used by people all over the world. By building one, you can create a useful tool that serves a broad audience.
  3. Customization: You can tailor your weather app to your preferences. Add unique features, themes, or functionalities that other weather apps might lack.
  4. Integration: Weather data is accessible through various APIs, providing an opportunity to learn how to integrate external data sources into your web applications.
  5. Problem Solving: Developing a weather app involves solving real-world challenges, such as handling data retrieval, formatting, and user interface design.

Weather App Using HTML CSS and JavaScript

Creating a weather app using HTML, CSS, and JavaScript involves fetching weather data from a weather API and displaying it on a web page. Here’s a step-by-step guide on how to create a simple weather app. You need to watch the complete video inside the you will learn everything step by step from scratch.

I hope you’ve watched the complete video hope you’ve learned something new from this tutorial. Let’s look at the source code that used inside the application.

Weather Forecast App Using HTML CSS and JavaScript

I tried to write simple codes so everyone understood it. Inside the application are forecast features. Also has many features such as validation, you can checkout the source code on below.

Design the HTML Structure

In your index.html file, create the basic structure for your weather app. You’ll need a place to display the weather information and a form to input the location (city, zip code, etc.).

 <div class="container">
      <div class="wrapper">
        <div class="img_section">
          <div class="default_info">
            <h2 class="default_day">Sunday</h2>
            <span class="default_date">18 September 2023 </span>
            <div class="icons">
              <img src="https://openweathermap.org/img/wn/[email protected]" alt="" />
              <h2 class="weather_temp">22°C</h2>
              <h3 class="cloudtxt">Overcast Clouds</h3>
            </div>
          </div>
        </div>
        <div class="content_section">
          <form>
            <input
              type="text"
              placeholder="Search Location"
              class="input_field"
            />
            <button type="submit" class="btn_search">Search</button>
          </form>

          <div class="day_info">
            <div class="content">
              <p class="title">NAME</p>
              <span class="value">United Kingdom</span>
            </div>
            <div class="content">
              <p class="title">TEMP</p>
              <span class="value">23°C</span>
            </div>
            <div class="content">
              <p class="title">HUMIDITY</p>
              <span class="value">2%</span>
            </div>
            <div class="content">
              <p class="title">WIND SPEED</p>
              <span class="value">2.92 Km/h</span>
            </div>
          </div>

          <div class="list_content">
            <ul>
              <li>
                <img src="https://openweathermap.org/img/wn/[email protected]" />
                <span>Sat</span>
                <span class="day_temp">23°C</span>
              </li>
              <li>
                <img src="https://openweathermap.org/img/wn/[email protected]" />
                <span>Sat</span>
                <span class="day_temp">23°C</span>
              </li>
              <li>
                <img src="https://openweathermap.org/img/wn/[email protected]" />
                <span>Sat</span>
                <span class="day_temp">23°C</span>
              </li>
              <li>
                <img src="https://openweathermap.org/img/wn/[email protected]" />
                <span>Sat</span>
                <span class="day_temp">23°C</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

Style Your Weather App

Add styles to your weather app by editing the style.css file. You can style it as you like to make it visually appealing.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&family=Ruda:wght@400;600;700&display=swap");

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: #37474f;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: "poppins", sans-serif;
}

.container {
  max-width: 800px;
  width: 100%;
  background-color: #232931;
  color: #fff;
  border-radius: 25px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.35);
}

.wrapper {
  display: grid;
  grid-template-columns: 3fr 4fr;
  grid-gap: 1rem;
}

.img_section {
  border-radius: 25px;
  background-image: url("../img/bg.jpg");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
  transform: scale(1.03) perspective(200px);
}

.img_section::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #5c6bc0 10%, #0d47a1 100%);
  opacity: 0.5;
  z-index: -1;
  border-radius: 25px;
}

.default_info {
  padding: 1.5rem;
  text-align: center;
}

.default_info img {
  width: 80%;
  object-fit: cover;
  margin: 0 auto;
}

.default_info h2 {
  font-size: 3rem;
}

.default_info h3 {
  font-size: 1.3rem;
  text-transform: capitalize;
}

.weather_temp {
  font-size: 4rem;
  font-weight: 800;
}

/* content section */
.content_section {
  padding: 1.5rem;
}

.content_section form {
  margin: 1.5rem 0;
  position: relative;
}

.content_section form input {
  width: 84%;
  outline: none;
  background: transparent;
  border: 1px solid #37474f;
  border-radius: 5px;
  padding: 0.7rem 1rem;
  font-family: inherit;
  color: #fff;
  font-size: 1rem;
}

.content_section form button {
  position: absolute;
  top: 0;
  right: 0;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  padding: 1rem 0.7rem;
  font-family: inherit;
  font-size: 0.8rem;
  outline: none;
  border: none;
  background: #5c6bc0;
  color: #fff;
  cursor: pointer;
}

.day_info .content {
  display: flex;
  justify-content: space-between;
  padding: 0.4rem 0;
}

.day_info .content .title {
  font-weight: 600;
}

.list_content ul {
  display: flex;
  justify-content: space-between;
  align-items: center;
  list-style-type: none;
  margin: 3rem 0rem;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.35);
}

.list_content ul li {
  padding: 0.5rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-radius: 1rem;
  transition: all 0.3s ease-in;
}

.list_content ul li:hover {
  transform: scale(1.1);
  background-color: #fff;
  color: #232931;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.35);
  cursor: pointer;
}

.list_content ul li img {
  width: 50%;
  object-fit: cover;
}

.icons {
  opacity: 0;
}

.icons.fadeIn {
  animation: 0.5s fadeIn forwards;
  animation-delay: 0.7s;
}

@keyframes fadeIn {
  to {
    transition: all 0.5s ease-in;
    opacity: 1;
  }
}

Fetch Weather Data with JavaScript

In your script.js file, you’ll use JavaScript to fetch weather data from a weather API. For this example, we’ll use the OpenWeatherMap API. You’ll need to sign up for a free API key at OpenWeatherMap to use their service.

"use strict";

const API = "YOUR API KEY";

const dayEl = document.querySelector(".default_day");
const dateEl = document.querySelector(".default_date");
const btnEl = document.querySelector(".btn_search");
const inputEl = document.querySelector(".input_field");

const iconsContainer = document.querySelector(".icons");
const dayInfoEl = document.querySelector(".day_info");
const listContentEl = document.querySelector(".list_content ul");

const days = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
];

// display the day
const day = new Date();
const dayName = days[day.getDay()];
dayEl.textContent = dayName;

// display date
let month = day.toLocaleString("default", { month: "long" });
let date = day.getDate();
let year = day.getFullYear();

console.log();
dateEl.textContent = date + " " + month + " " + year;

// add event
btnEl.addEventListener("click", (e) => {
  e.preventDefault();

  // check empty value
  if (inputEl.value !== "") {
    const Search = inputEl.value;
    inputEl.value = "";
    findLocation(Search);
  } else {
    console.log("Please Enter City or Country Name");
  }
});

async function findLocation(name) {
  iconsContainer.innerHTML = "";
  dayInfoEl.innerHTML = "";
  listContentEl.innerHTML = "";
  try {
    const API_URL = `https://api.openweathermap.org/data/2.5/weather?q=${name}&appid=${API}`;
    const data = await fetch(API_URL);
    const result = await data.json();
    console.log(result);

    if (result.cod !== "404") {
      // display image content
      const ImageContent = displayImageContent(result);

      // display right side content
      const rightSide = rightSideContent(result);

      // forecast function
      displayForeCast(result.coord.lat, result.coord.lon);

      setTimeout(() => {
        iconsContainer.insertAdjacentHTML("afterbegin", ImageContent);
        iconsContainer.classList.add("fadeIn");
        dayInfoEl.insertAdjacentHTML("afterbegin", rightSide);
      }, 1500);
    } else {
      const message = `<h2 class="weather_temp">${result.cod}</h2>
      <h3 class="cloudtxt">${result.message}</h3>`;
      iconsContainer.insertAdjacentHTML("afterbegin", message);
    }
  } catch (error) {}
}

// display image content and temp
function displayImageContent(data) {
  return `<img src="https://openweathermap.org/img/wn/${
    data.weather[0].icon
  }@4x.png" alt="" />
    <h2 class="weather_temp">${Math.round(data.main.temp - 275.15)}°C</h2>
    <h3 class="cloudtxt">${data.weather[0].description}</h3>`;
}

// display the right side content
function rightSideContent(result) {
  return `<div class="content">
          <p class="title">NAME</p>
          <span class="value">${result.name}</span>
        </div>
        <div class="content">
          <p class="title">TEMP</p>
          <span class="value">${Math.round(result.main.temp - 275.15)}°C</span>
        </div>
        <div class="content">
          <p class="title">HUMIDITY</p>
          <span class="value">${result.main.humidity}%</span>
        </div>
        <div class="content">
          <p class="title">WIND SPEED</p>
          <span class="value">${result.wind.speed} Km/h</span>
        </div>`;
}

async function displayForeCast(lat, long) {
  const ForeCast_API = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${long}&appid=${API}`;
  const data = await fetch(ForeCast_API);
  const result = await data.json();
  // filter the forecast
  const uniqeForeCastDays = [];
  const daysForecast = result.list.filter((forecast) => {
    const forecastDate = new Date(forecast.dt_txt).getDate();
    if (!uniqeForeCastDays.includes(forecastDate)) {
      return uniqeForeCastDays.push(forecastDate);
    }
  });
  console.log(daysForecast);

  daysForecast.forEach((content, indx) => {
    if (indx <= 3) {
      listContentEl.insertAdjacentHTML("afterbegin", forecast(content));
    }
  });
}

// forecast html element data
function forecast(frContent) {
  const day = new Date(frContent.dt_txt);
  const dayName = days[day.getDay()];
  const splitDay = dayName.split("", 3);
  const joinDay = splitDay.join("");

  // console.log(dayName);

  return `<li>
  <img src="https://openweathermap.org/img/wn/${
    frContent.weather[0].icon
  }@2x.png" />
  <span>${joinDay}</span>
  <span class="day_temp">${Math.round(frContent.main.temp - 275.15)}°C</span>
</li>`;
}

Open your index.html file in a web browser, and you should have a basic weather app that allows users to input a location and fetch weather data from the OpenWeatherMap API.

Remember to replace 'YOUR_API_KEY' it with your actual API key from OpenWeatherMap.

You May Also Like:

This is a simple example, and you can expand on it by adding more features, like displaying weather icons or forecasts, handling errors gracefully, and improving the user interface.

Deployment

Once you are satisfied with your weather app, it’s time to deploy it to the web. You can choose from various hosting options, including free hosting services or deploying to your own server. Make sure to secure your app by using HTTPS.

Future Enhancements

A weather app is a project that can always be improved and expanded. Consider adding features like weather alerts, historical weather data, or integration with other services like Google Maps for a richer user experience.

Conclusion

Building a weather app with HTML CSS and JavaScript is not only a great way to apply your web development skills but also a practical project that can benefit users worldwide. By following the steps outlined in this article, you can create a dynamic and visually appealing weather app that provides accurate and timely weather information.

Remember that web development is an ever-evolving field, so explore new technologies and techniques to enhance your app further. With dedication and creativity, your weather app can become a valuable tool for users and a testament to your web development abilities. Happy coding!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.