Retrieve and display API via event listener

Hello All,

I have been attempting to grab data from the OpenWeather API and display it in a simple JS, HTML and CSS app. My issue is I currently am using an event listener on window load to check navigator for latitude and longitude to retrieve the appropriate weather data. However,
I would like to set up an event listener on a form so that the user can submit a zip code and I can set that to a variable and use that to retrieve the requested data from the API.

I will attach the GitHub repo with the current working code and the code I have been trying to use (commented out starting at line 62 in script.js. The form is commented out at lines 38-42 in index.html)

While debugging it appears like the API returns the requested data but the data is only displayed briefly and then the page reloads. It is so brief that the data can only be seen if I set up a breakpoint and console log it.

Ultimately, I’m not sure why the data is displayed properly with the window event listener but not when I try and use an event listener on a form?

I’m not looking for a solution but if someone would be kind enough to explain what I’m not understanding and possibly point me to the proper documentation I would be very grateful.

Thanks in advance!

link to repo:

script.js bellow

const navHamburger = document.querySelector(".hamburger");
const navEl = document.querySelector("nav");
const contentEl = document.querySelector(".content");
const hamburgerBars = document.getElementsByTagName("span");
const key = "7fc25908d302657f051ed31e21a3935e";
const degSection = document.querySelector(".deg-section");
const temp = document.querySelector(".temp");
let tempSpan = document.querySelector(".temp span");
let tempDegree = document.querySelector(".temp-degree");
const tempIcon = document.querySelector(".temp-icon");
const localTimezone = document.querySelector(".location-timezone");
const tempDescription = document.querySelector(".temp-description");

function navToggle(){
    navHamburger.addEventListener("click", function() {
    navEl.classList.toggle("open");
    contentEl.classList.toggle("shift");  
    hamburgerBars[0].classList.toggle("changeFirstBar");
    hamburgerBars[1].classList.toggle("changeSecondBar");
    hamburgerBars[2].classList.toggle("changeThirdBar");
    })
}
navToggle();

window.addEventListener("load", () => {
let lon;
let lat;

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
    lon = position.coords.longitude;
    lat = position.coords.latitude;
    const api = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${key}`

    fetch(api)
    .then(response => response.json())

    .then(data => {
        let fTemp = Math.floor(((data.main.temp) * 9/5) - 459.67);
        let cTemp = Math.floor((fTemp - 32) / 1.8000);
        let weatherLocation = data.name;
        let icon = data.weather[0].icon;
        tempDegree.textContent = fTemp;
        tempDescription.textContent = weatherLocation;
        tempIcon.src = `http://openweathermap.org/img/wn/${icon}@2x.png`;
        localTimezone.textContent = data.weather[0].description;

        temp.addEventListener("click", () => {
            if(tempSpan.textContent === "F") {
                tempSpan.textContent = "C";
                tempDegree.textContent = cTemp;
            } else {
                tempSpan.textContent = "F";
                tempDegree.textContent = fTemp;
            }
        })        
    })
  })
 }
})

// document.querySelector(".zipSubmit").addEventListener("click", () => {
//     let zip = document.querySelector("#zip").value;
//     console.log(zip)
//         console.log(zip)
//         const api = `http://api.openweathermap.org/data/2.5/weather?zip=${zip},&appid=${key}`
//         fetch(api)
//         .then(response => response.json())
    
//         .then(data => {
//             let fTemp = Math.floor(((data.main.temp) * 9/5) - 459.67);
//             let weatherLocation = data.name;
//             let icon = data.weather[0].icon;
//             tempDegree.textContent = fTemp;
//             tempDescription.textContent = weatherLocation;
//             tempIcon.src = `http://openweathermap.org/img/wn/${icon}@2x.png`;
//             localTimezone.textContent = data.weather[0].description;    
//         })
//      })
    
    
    //  temp.addEventListener("click", () => {
    //     const api = `api.openweathermap.org/data/2.5/weather?zip=${zip},us&appid=${key}`
    //     fetch(api)
    //     .then(response => response.json())
    
    //     .then(data => {
    //         let fTemp = Math.floor(((data.main.temp) * 9/5) - 459.67);
    //         let cTemp = Math.floor((fTemp - 32) / 1.8000);  
            
    //         if(tempSpan.textContent === "F") {
    //             tempSpan.textContent = "C";
    //             tempDegree.textContent = cTemp;
    //         } else {
    //             tempSpan.textContent = "F";
    //             tempDegree.textContent = fTemp;
    //         }
    //     })
    // }) 

index.html bellow

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

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Weather Forecast App</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <nav class="nav">
    <ul class="menu">
      <li class="menu__item">Home</li>
      <li class="menu__item">About</li>
      <li class="menu__item">Weather API</li>
      <li class="menu__item">Contact</li>
    </ul>
    <div class="hamburger">
      <span class="first-bar"></span>
      <span class="second-bar"></span>
      <span class="third-bar"></span>
    </div>
  </nav>
  <main class="content">
    <div class="location">
      <h4 class="location-timezone">Loading...</h4>
      <img class="temp-icon" src=http://openweathermap.org/img/wn/11d@2x.png>
    </div>
    <div class="temp">
      <div class="deg-section">
      <h2 class="temp-degree">Loading...</h2>
      <span>F</span>
    </div>
      <div class="temp-description">Loading...</div>
    </div>
    <!-- <form>
      <label for="zip">Enter Zip:</label>
      <input type="number" id="zip" name="zipCode"><br><br>
      <input class="zipSubmit" type="submit" value="Submit">
    </form> -->
  </main>
  <script src="script.js"></script>
</body>

</html>

Hello All,

I asked a previous question and feel I may have been unclear. I will ask in a different way here and try to be clearer and more succinct.

Does anyone know why an API request would display data properly when retrieved via a window.addEvenListener("load") but not retrieve and display data on a document."ElementToBeClicked.addEventListener("click")?

I am still learning so forgive me if I am asking something overly simple. I have been racking my brain trying to understand what I am missing.

I will add a link to a fiddle for clarification. It contains the working code and code I am trying to make work commented out.

Thanks in advance for any advice!

https://jsfiddle.net/q0dmt398/91/

That API endpoint is responding with a 404.

I think you forgot https:// in the URL.

Thanks for pointing that out Colin.

It doesn’t do that on my local port but the fiddle doesn’t like it for some reason. I did update the code to include that https:// but unfortunately that is not it.

I’m sure there is something going on I should know and it is driving me crazy but that is the fun (and sometimes pain :slight_smile: of JS sometimes!

When you’re clicking submit button you’re also submitting the form and form has default action - refresh the page.
Event.preventDefault() - Web APIs | MDN

jenovs,

Embarrassed but very grateful for the help! :sweat_smile:

The pain will help me remember this going forward though. Thank you again for taking the time to help!

Can I ask if you knew this from experience or did you see this happening while debugging? I am obviously not the best at debugging and would be interested in your process.

Thanks!

I know it from experience. I didn’t have to run your code. I knew where the problem was after reading this:

the API returns the requested data but the data is only displayed briefly and then the page reloads.

Awesome. Easy fix for that, keep coding :slight_smile:

Thanks again.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.