Зміст курсу
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
Creating a Real-time Weather App with HTML + JavaScript
In this chapter, you'll learn about accessing basic weather information about a city, such as its current temperature, and information, such as whether it's cloudy, foggy, or sunny. You can obtain this information through a free API, call its functions via Javascript, and then display it on a web page. Let's dive into it.
Finding a Weather API
Our first priority is finding a vendor willing to allow us to use their weather data in our app. Fortunately, numerous companies specialize in creating weather apps, and most offer both a free package and premium memberships that vary in price according to the services/features.
What is the OpenWeather API?
In this instance, one of the most well-liked free options is OpenWeatherMap. It has been working with deep meteorological data as an IT and data science collective since 2014. Through lightning-fast APIs, OpenWeather offers accurate historical, present-day, and anticipated weather data for every location on Earth.
Before using its features, you must first register for an API key. Follow the steps on this page to get your API key.
Creating the Markup of the Page
We will write the markup to get the essential weather information now that you have the API key.
index
index
index
As you can see, this is a basic markup with an input form and a submit button. For a change, we've linked the javascript file as an external file, so before moving into the Javascript code, let's add the styles in the index.css
file.
index
index
index
Creating the functionality to get the Weather Information
First, in the script, we initialize the variables that get the HTML elements on the page on the window’s onload event.
index
index
index
Then in the above piece of code, the event listener to the form submits an event, and then in onsubmit
, the page refresh is prevented with default event handling of form submission.
Fetching the data from the API
This code gets the value of the city name in the input city field and then you assign a variable with the API URL followed by the city parameter and the API key.
Then the api is called along with the parameters with an ajax call and it returns a series of JSON objects.So we get the details to an <li>
element and append it to the parent <li>
.
We also check if the input of the city is in the correct format. If it’s not, we display an error message.Here is a screenshot of some of the outputs.
This is just a basic app; you can continue working on it for more features.
Дякуємо за ваш відгук!