Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This is the last and most advanced code example, let's get to it.
- // A weather app
- const weatherForm = document.querySelector(".weatherForm"); // We need all of our elements going.
- const cityInput = document.querySelector(".cityInput"); // This method returns the first element that matches a CSS selector.
- const card = document.querySelector(".card");
- const apiKey = ""; // We are using an API, so put your openweathermap.org key in there.
- // But you don't need to test it yourself, just see if the code looks fine and makes sense or not.
- weatherForm.addEventListener("submit", async event => { // We want to make sure this is asynchronous, so we can do other things in the background, and non-code-blocking and stuff.
- event.preventDefault(); // In the document, this uses forms, so when we submit, it automatically refreshes the page, but we don't want that, it does that by default.
- const city = cityInput.value; // What we wrote in the input.
- if (city) { // If it's not empty.
- try { // Error handling, it speaks for itself.
- const weatherData = await getWeatherData(city); // Call the function asynchronously, because there is 'await'.
- displayWeatherInfo(weatherData);
- } catch(error) { // In case there are any errors.
- console.error(error);
- displayError(error);
- }
- } else { // If it is empty.
- displayError("Please Enter A City");
- }
- });
- async function getWeatherData(city) { // We passed in the city earlier, we make sure this is async, to prevent code-blocking, that's one of the reasons dealing with APIs are dangerous.
- const apiURL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`; // Anyways that's the URL we need that will return the data.
- // I never explained, we need to register an account to get an API key, this is to prevent raids/spams/bots and etc (I think).
- const response = await fetch(apiURL);
- if (!response.ok) { // If it was successful, put an ! if you want to see if it's NOT successful.
- throw new Error("Could not fetch weather data."); // Ouch
- }
- return await response.json(); // It will convert the response to JSON given by the API.
- }
- function displayWeatherInfo(data) { // Weather information
- const {
- name: city,
- main: {temp, humidity},
- weather: [{description, id}]
- } = data; // Well this is an object, we have nested objects inside, all those unknown variables come from the data that was passed down when calling this function.
- // The variable doesn't need a name because it's an array that already has assigned names, which are in order, from the JSON conversion from the API.
- card.textContent = ""; // Clear the content.
- card.style.display = "flex"; // Make it visible, basically.
- const cityDisplay = document.createElement("h1"); // Again, you understand what it does.
- const tempDisplay = document.createElement("p");
- const humidityDisplay = document.createElement("p");
- const descDisplay = document.createElement("p");
- const weatherEmoji = document.createElement("p");
- cityDisplay.textContent = city;
- tempDisplay.textContent = `${(temp - 273.15).toFixed(2)}°C`; // We convert this to celsius.
- humidityDisplay.textContent = `Humidity: ${humidity}%`;
- descDisplay.textContent = description;
- weatherEmoji.textContent = getWeatherEmoji(id);
- cityDisplay.classList.add("cityDisplay"); // We add them to a class, so we can style them in the CSS.
- tempDisplay.classList.add("tempDisplay");
- humidityDisplay.classList.add("humidityDisplay");
- descDisplay.classList.add("descDisplay");
- weatherEmoji.classList.add("weatherEmoji");
- card.appendChild(cityDisplay); // Now we add it to the card div.
- card.appendChild(tempDisplay);
- card.appendChild(humidityDisplay);
- card.appendChild(descDisplay);
- card.appendChild(weatherEmoji);
- }
- function getWeatherEmoji(weatherId) {
- switch (true) { // A switch statement makes everything easier if you know there will be a lot of if-statements.
- case (weatherId >= 200 && weatherId < 300): return "⛈️"; // This is given to us from the API, in their website, they explain these IDs, we give an emoji for it to display to the user.
- case (weatherId >= 300 && weatherId < 400): return "🌧️";
- case (weatherId >= 500 && weatherId < 600): return "🌧️";
- case (weatherId >= 600 && weatherId < 700): return "🌨️";
- case (weatherId >= 700 && weatherId < 800): return "🌫️";
- case (weatherId === 800): return "☀️";
- case (weatherId >= 801 && weatherId < 810): return "☁️";
- default: return "❓"; // If it doesn't match any.
- }
- }
- function displayError(message) { // Displays the error with a given message.
- const errorDisplay = document.createElement("p"); // I already explained about all of this.
- errorDisplay.textContent = message;
- errorDisplay.classList.add("errorDisplay");
- card.textContent = "";
- card.style.display = "flex"; // For CSS styling, we set it.
- card.appendChild(errorDisplay);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement