Advertisement
SamIsWicked

JavaScript Weather App

Jan 13th, 2025
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 5.14 KB | Source Code | 0 0
  1. // This is the last and most advanced code example, let's get to it.
  2. // A weather app
  3.  
  4. const weatherForm = document.querySelector(".weatherForm"); // We need all of our elements going.
  5. const cityInput = document.querySelector(".cityInput"); // This method returns the first element that matches a CSS selector.
  6. const card = document.querySelector(".card");
  7. const apiKey = ""; // We are using an API, so put your openweathermap.org key in there.
  8. // But you don't need to test it yourself, just see if the code looks fine and makes sense or not.
  9. 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.
  10.     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.
  11.  
  12.     const city = cityInput.value; // What we wrote in the input.
  13.  
  14.     if (city) { // If it's not empty.
  15.  
  16.         try { // Error handling, it speaks for itself.
  17.             const weatherData = await getWeatherData(city); // Call the function asynchronously, because there is 'await'.
  18.             displayWeatherInfo(weatherData);
  19.         } catch(error) { // In case there are any errors.
  20.             console.error(error);
  21.             displayError(error);
  22.         }
  23.  
  24.     } else { // If it is empty.
  25.         displayError("Please Enter A City");
  26.     }
  27. });
  28.  
  29. 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.
  30.     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.
  31.     // 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).
  32.     const response = await fetch(apiURL);
  33.    
  34.     if (!response.ok) { // If it was successful, put an ! if you want to see if it's NOT successful.
  35.         throw new Error("Could not fetch weather data."); // Ouch
  36.     }
  37.  
  38.     return await response.json(); // It will convert the response to JSON given by the API.
  39. }
  40.  
  41. function displayWeatherInfo(data) { // Weather information
  42.     const {
  43.         name: city,
  44.         main: {temp, humidity},
  45.         weather: [{description, id}]
  46.     } = 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.
  47.     // 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.
  48.  
  49.     card.textContent = ""; // Clear the content.
  50.     card.style.display = "flex"; // Make it visible, basically.
  51.  
  52.     const cityDisplay = document.createElement("h1"); // Again, you understand what it does.
  53.     const tempDisplay = document.createElement("p");
  54.     const humidityDisplay = document.createElement("p");
  55.     const descDisplay = document.createElement("p");
  56.     const weatherEmoji = document.createElement("p");
  57.    
  58.     cityDisplay.textContent = city;
  59.     tempDisplay.textContent = `${(temp - 273.15).toFixed(2)}°C`; // We convert this to celsius.
  60.     humidityDisplay.textContent = `Humidity: ${humidity}%`;
  61.     descDisplay.textContent = description;
  62.     weatherEmoji.textContent = getWeatherEmoji(id);
  63.  
  64.     cityDisplay.classList.add("cityDisplay"); // We add them to a class, so we can style them in the CSS.
  65.     tempDisplay.classList.add("tempDisplay");
  66.     humidityDisplay.classList.add("humidityDisplay");
  67.     descDisplay.classList.add("descDisplay");
  68.     weatherEmoji.classList.add("weatherEmoji");
  69.  
  70.     card.appendChild(cityDisplay); // Now we add it to the card div.
  71.     card.appendChild(tempDisplay);
  72.     card.appendChild(humidityDisplay);
  73.     card.appendChild(descDisplay);
  74.     card.appendChild(weatherEmoji);
  75. }
  76.  
  77. function getWeatherEmoji(weatherId) {
  78.     switch (true) { // A switch statement makes everything easier if you know there will be a lot of if-statements.
  79.         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.
  80.         case (weatherId >= 300 && weatherId < 400): return "🌧️";
  81.         case (weatherId >= 500 && weatherId < 600): return "🌧️";
  82.         case (weatherId >= 600 && weatherId < 700): return "🌨️";
  83.         case (weatherId >= 700 && weatherId < 800): return "🌫️";
  84.         case (weatherId === 800): return "☀️";
  85.         case (weatherId >= 801 && weatherId < 810): return "☁️";
  86.  
  87.         default: return "❓"; // If it doesn't match any.
  88.     }
  89. }
  90.  
  91. function displayError(message) { // Displays the error with a given message.
  92.     const errorDisplay = document.createElement("p"); // I already explained about all of this.
  93.     errorDisplay.textContent = message;
  94.     errorDisplay.classList.add("errorDisplay");
  95.  
  96.     card.textContent = "";
  97.     card.style.display = "flex"; // For CSS styling, we set it.
  98.     card.appendChild(errorDisplay);
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement