Build A Weather App Using JavaScript [For Beginners] ☀️🌤️

I started JS practice to get more knowledge about JS. so I searched for some projects on YouTube and I found the weather app in JavaScript. So I watched it, built the project, and did some modifications.

To get weather data we used Openweathermap’s weather API. Just sign-up yourself and create an account then go to this page: https://home.openweathermap.org/api_keys.

Enter any API key name and Generate key.

weather api, weather app in javascript, Build A Weather App Using JavaScript

Now let’s code.

Code

First, we design UI, so open your favorite code editor and make index.html and make look like following,

index.html

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no" />
    <title>Wather App</title>
    <link rel="stylesheet" href="style.css">

</head>

<body>

    <div class="app-wrap">
        <header>
            <input type="text" class="search-box" placeholder="Search for a city..." autocomplete="off">
        </header>

        <main>
            <section class="location">
                <div class="city">
                    City, Country
                </div>
                <div class="date">
                    Day, Month Date, Year
                </div>
            </section>
            <div class="current">
                <div class="temp">Temp<span>°c</span></div>
                <div class="weather-icon">
                    <img alt="weather_icon">
                </div>
                <div class="weather">Weather</div>
                <div class="description">Weather_description</div>
                <div class="hi-low">min_temp°c/ max_temp°c</div>
            </div>
        </main>
    </div>

    <script src="main.js"></script>

</body>


</html>

Now create style.css and write the following code.

style.css

@import url("https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;700;900&display=swap");
*{
  margin:0;
  padding:0;
  box-sizing: border-box;
}

body{
  font-family: 'montserrat',sans-serif;
  background-image: url('bg.jpg');
  background-size: cover;
  background-position: top center;
}

.app-wrap{
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-image: linear-gradient(to bottom, rgba(0,0,0,0.3),rgba(0,0,0,0.6));
}

header{
  display:flex;
  justify-content: center;
  align-items: center;
  padding: 50px 15px 15px;
}

header input{
  width: 100%;
  max-width: 280px;
  padding: 10px 15px;
  border:none;
  outline: none;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  color: #fff;
  border-bottom: 3px solid #df8e00;
  font-size: 20px;
  font-weight: 300;
  transition: 0.2s ease-out;
}

header input:focus{
  background-color: rgba(255, 255, 255,0.6);
}

header input::placeholder{
  color:rgba(255, 255, 255,0.6);
}

main{
  flex: 1 1 100%;
  padding: 25px 25px 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.location .city{
  color: #fff;
  font-size:32px;
  font-weight: 500;
  margin-bottom: 5px;
}

.location .date{
  color:#fff;
  font-size: 16px; 
}

.current .temp{
  color:#fff;
  font-size: 102px;
  font-weight: 900;
  margin: 10px 0px;
  text-shadow: 2px 10px rgba(0,0,0,0.6);
}

.current .temp span{
  font-weight: 500;
}

.current .weather{
  color:#fff;
  font-size: 32px;
  font-weight: 700;
  font-style: italic;
  margin-bottom: 5px;
  text-shadow: 0px 3px rgba(0,0,0,0.4);
}

.current .description{
  color:#fff;
  font-size: 16px; 
  margin-bottom: 15px;
  text-transform: capitalize;
}

.current .hi-low{
  color:#fff;
  font-size: 24px;
  font-weight: 500;
  text-shadow: 0px 4px rgba(0, 0, 0, 0.4);
}

Let’s write JavaScript code.

main.js

// paste your secret key
const api = {
    key: "9f****************************", // your secrete key here
    base_url: "https://api.openweathermap.org/data/2.5/",
}

// selecting the inputbox
const searchbox = document.querySelector(".search-box");

//adding keypress event listener to inputbox
searchbox.addEventListener("keypress", setQuery);

// when user enter city and and click the enter key then getResults function will invoked
function setQuery(e) {
    // 13 is key code for enter key
    if (e.keyCode == 13) {
        // calling getResults function and passing city name when click enter key
        getResults(searchbox.value);
        // console.log(searchbox.value);
    }
}

// fetching the data from weather api
function getResults(query) {
    // qeury carries city name and we passes to the Api url so final url be looks like this 
    // https://api.openweathermap.org/data/2.5/weather?q=London&unit=metric&APPID=9f9189f3ea73cf55b8cc02b2d5091f72

    //so query passes to this URL to get data for the user-entered city name

    fetch(`${api.base_url}weather?q=${query}&units=metric&APPID=${api.key}`)
        .then(weather => {
            return weather.json();
        }).then(displayResults); // passing response (weather) object
}



function displayResults(weather) {
    // console.log(typeof weather);

    // accessing weather object and getting data

    // selecting the element and setting the city and country name from api
    let city = document.querySelector('.location .city');
    city.innerText = `${weather.name}, ${weather.sys.country}`;

    // setting current date, see the dateBuilder() function bellow
    let now = new Date();
    let date = document.querySelector('.location .date');
    date.innerText = dateBuilder(now);

    // selecting the element and setting the current temperature of city
    let temp = document.querySelector('.current .temp');
    temp.innerHTML = `${Math.round(weather.main.temp)}<span>°c</span>`;

    // selecting the element and setting the current weather of city like, 'sunny', 'cloudy'
    let weather_el = document.querySelector('.current .weather');
    weather_el.innerText = weather.weather[0].main;

    // selecting the element and setting the current weather description of city
    let weather_description = document.querySelector('.current .description');
    weather_description.innerText = weather.weather[0].description;

    // selecting the element and setting the current weather image/icon of city
    let weather_icon = document.querySelector('.current .weather-icon img');
    //console.log(weather.weather[0].icon);
    weather_icon.src = `http://openweathermap.org/img/wn/${weather.weather[0].icon}@4x.png`;

    // selecting the element and setting the current min and max temperature of city
    let hilow = document.querySelector('.current .hi-low');
    hilow.innerText = `${Math.round(weather.main.temp_min)}°c / ${Math.round(weather.main.temp_max)}°c`;

}

// returns today's date
function dateBuilder(d) {
    let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    let day = days[d.getDay()];
    let date = d.getDate();
    let month = months[d.getMonth()];
    let year = d.getFullYear();

    return `${day}, ${date} ${month} ${year}`;
}

Output

build a weather app using javascript

Reference: https://youtu.be/n4dtwWgRueI

GitHub repo: https://github.com/SoniArpit/weather-app-js

Hope you like this simple weather app in JavaScript. Share it with your friends. Thank you.

Also check,