Weather App Using Html,Css And JavaScript
Welcome back to the kitchen guys! The year’s coming to an end and it’s the Arctic outside! So before frostnip renders us unable to do anything, let’s end the year with another awesome yet simple cuisine.
Today, we’re going to make a Real-time Weather update website Using Html,Css And JavaScript! It will give us the weather details of the city entered along with a beautiful picture of the city. So, take off your gloves, and let’s get right into it!
Before I go off showing you the code, I need to tell you about my code editor and trust me VS Code did NOT pay me for the promotion I just love it so much that I HAVE to recommend it. VS Code is one of the best IDEs, with so many extensions and cool features that will make your coding process smooth and you’ll just glide through it. So, use it if you have it or download it from here.
Portfolio Website using HTML and CSS (Source Code)
Let’s begin with making a search bar, to enter the city, and a div to give the output. I made an HTML file and named it ‘index.html’, you can choose the name as per your wish. In it goes the following piece of code:
Html Code For Weather App
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Weather App</title> <link rel="stylesheet" href="./styles.css"> <script src="./script.js" defer></script> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet"> </head> <body> <div class="card"> <div class="search"> <input type="text" class="search-bar" placeholder="Search"> <button> <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10.442 10.442a1 1 0 011.415 0l3.85 3.85a1 1 0 01-1.414 1.415l-3.85-3.85a1 1 0 010-1.415z" clip-rule="evenodd"></path><path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 100-11 5.5 5.5 0 000 11zM13 6.5a6.5 6.5 0 11-13 0 6.5 6.5 0 0113 0z" clip-rule="evenodd"></path></svg> </button> </div> <div class="weather loading"> <h2 class="city">Weather in Delhi</h2> <h1 class="temp">13°C</h1> <div class="description">Cloudy</div> <div class="humidity">Humid</div> <div class="wind">Fast</div> </div> </div> </body> </html>
Discussing the meta tags always gets messy and complicated. No worries, you can always just copy-paste that, or use VS Code extensionto automatically generate it for you every time you open an HTML file. We have just changed the ‘title’ and connected the file to ‘styles.css’ and ‘script.js’. I’ll explain what those are later.
10+ Javascript Projects For Beginners With Source Code
Also, I’m not predicting the weather here. We’re writing ‘Delhi’ and ’13°C‘ right now just to get an idea of how the final results would look. Obviously not permanent.
Our webpage is looking something like this right now:
Now if you want to know how I put that magnifying glass as the search button, I used the VS Code Icon Extension to get the code for the image. If you can’t use that, just find some cool free icons here. In any case, you’ll have to set the dimensions yourself as per your needs.
This is the best part about web development. Something looking so bare and boring like this and we, developers, turn it into a piece of art, into something visually appealing. And what’s our ingredient for that? That’s right! CSS! So, make a ‘styles.css’ and let’s code.
Css Code For Weather App
*{ padding: 0; margin: 0; box-sizing: border-box; -webkit-font-smoothing: antialiased; } body{ display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: rgb(41, 39, 39); font-family: 'Open Sans', sans-serif; background-image: url(https://source.unsplash.com/random/1600x900/?landscape); }
Flex is a gift of God. Solves all our layout problems. Now if you’ll run your page, you’ll notice the background keeps changing every time you reload. This is because of the URL we have inserted in the ‘background-image’ parameter of ‘body’. Unsplash is a platform to get free images for all your needs, and we used its API to import a random picture when we reload the page. I’ve written ‘landscape’ to get some cool sceneries, but you can try something like ‘technology’ or ‘fruits’ too!
Pretty innit?
Let’s work on our search bar and the output text now. Here comes the CSS!
.card{ background: rgba(0, 0, 0, 0.884); color: white; padding: 1.5rem; border-radius: 30px; width: 100%; max-width: 420px; margin: 1rem; } .search{ display: flex; align-items: center; justify-content: center; } .search button{ margin: 1rem; border-radius: 50%; border: none; height: 2.5rem; width: 2.5rem; outline: none; background-color: rgba(92, 88, 88, 0.644); color: white; } .search button:hover{ background-color: rgb(92, 88, 88); cursor: pointer; transition: 0.2s ease-in-out; } input.search-bar { border: none; outline: none; padding: 1rem 1rem; border-radius: 50px; width: 15rem; height: 2.5rem; background-color: rgba(92, 88, 88, 0.644); color: white; font-family: inherit; font-size: 100%; } .description{ text-transform: capitalize; }
A pro developer doesn’t need to see the end product, he can visualize it just by looking at his code. And since we’re not pros, we’ll definitely look at how’s our site looking.
100+ JavaScript Projects With Source Code ( Beginners to Advanced)
This Unsplash really is something. Look how beautiful the background looks. Well, that’s it for the looks folks. I’ll tell you what we plan to do next. We’ll be using the OpenWeather API to access real-time weather data for the location entered. That’s right, you’ll be learning APIs here too. Yeah yeah I know… I’m so cool I always send my readers back with more knowledge than they come expecting.
So, when you’ll open the OpenWeather website, first sign up/login. Click on your profile after you’re done, and head to ‘My API keys’. You’ll find a long alphanumeric string under the head Key. That’s your API key, and you’ll be needing this so copy-paste this somewhere for now.
Now click on API in the navigation bar of the site and find Current Weather Data. Click on ‘API doc’. You’ll find this:
ADVERTISEMENT
ADVERTISEMENT
This is the URL we’ll use to call the API. You can test it by copying the URL and replacing the {city name} with any city you want and {API Key} with your API key, the one you copied earlier. Paste this in your browser and you should see a page with data about the city you entered.
ADVERTISEMENT
ADVERTISEMENT
The format seems weird as it’s actually a ‘.json’ file. Now that we understand how this API works, we’ll jump on the coding part. If you wish to know about the API and it’s other features more, you can read the documentation on their website.
ADVERTISEMENT
Here enters JavaScript, who will be helping us integrate this API data into our webpage. Let’s make a room for him in a file named ‘script.jss’.
JavaScript Code For Weather App
let weather = { "apiKey": "e2c1d873e17655abe9c9bdf6946db59d", fetchWeather: function (city) { fetch("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid="+ this.apiKey) .then((response)=>response.json()) .then((data)=>this.displayWeather(data)); }, displayWeather: function (data) { const {name}=data; const {icon,description}=data.weather[0]; const {temp,humidity}=data.main; const {speed}=data.wind; // console.log(name,description,icon,temp,humidity,speed); document.querySelector(".city").innerText="Weather in " + name; document.querySelector(".description").innerText=description; document.querySelector(".temp").innerText=temp + "°C"; document.querySelector(".humidity").innerText="Humidity: "+humidity+"%"; document.querySelector(".wind").innerText="Wind Speed: "+speed+" km/h"; document.querySelector(".weather").classList.remove("loading"); document.body.style.backgroundImage="url('https://source.unsplash.com/random/1600x900/?"+ name +")"; }, search: function () { this.fetchWeather(document.querySelector(".search-bar").value); } };
We create an object named ‘weather’ to store a number of variables and data. First, we store our API Key in a variable. The ‘fetchWeather’ function will return the data in the ‘.json’ file and pass it in the ‘displayWeather’ function. This function gets the desired data from the file and replaces the sample text in our HTML file with the corresponding values.
50+ Html ,Css & Javascript Projects With Source Code
We also edit the Unspalsh URL we were using to get a background image by replacing the ‘landscape’ with the name of the city entered. It will then return a picture associated with the location as the background image of our site. The ‘search’ function will call the ‘fetchWeather’ function which is, again, returning the ‘.json’ file for the location entered from the API.
document.querySelector(".search button").addEventListener("click", function () { weather.search(); }); document.querySelector(".search-bar").addEventListener("keyup",function(event) { if (event.key=="Enter") { weather.search() } });
This lets our site knows that when the user clicks the button or hits ‘Enter’ on the keyboard, it will run the search function. Now we’ll actually call ‘fetchWeather’ ourself so that there is something to display when the site is first opened. I’ll be calling the function for Delhi, since that’s where I live and I need to know it’s temperature as soon as I open my site. You can search for the place of your residence.
weather.fetchWeather("Delhi");
Okay now here’s one optional thing. You’ll notice that when we reload the site, even though it’s only for a fraction of a second, it shows our sample text written in the ‘index.html’ file. To avoid that, I’ll put this piece of code in my ‘styles.css’.
.loading{ visibility: hidden; } .loading::after{ visibility: visible; content: "Loading..."; color: white; }
And we’re done! Now we can check the weather of places from all across the globe. We also get a picture of that place as a bonus! Let’s test it.
Seems like the entire world is freezing. Compared to that, I shouldn’t be complaining about the cold here. Alright folks that’s it from my side, but you don’t restrict yourself. Figure out how to show images of clouds or of the sun along with the temperature. Try to display more data such as pressure, visibility, time zone, etc. Play with the colours, the borders, margins, padding, everything. Hope you learned something and most importantly hope you enjoyed building this little project.. Don’t forget to drop your comments down below and feel free to reach out to me on Instagram. Merry Christmas and I’ll see you soon!
-Akshat Sharma