0

I am creating an app that allows the user to check the local weather and temperature in celsius or fahrenheit. However, I am having a problem when toggling between the two unit types when the temperature is clicked on. This is the link to my demo.

And here is my Javascript code:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    $.getJSON("https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude + "&units=imperial&appid=a62849f462c6573114f32a691f5d3c3f", function(json) {
      var all = JSON.stringify(json);
      var weather = JSON.stringify(json.weather[0]["description"]);
      weather = weather.slice(1, -1);
      var tempFahrenheit = JSON.stringify(json.main.temp);
      var tempCelsius = JSON.stringify(json.main.temp * 2);
      $("#weather").html(weather);
      $("#temp").html(Math.floor(tempFahrenheit) + " &deg;<span id='units'>F</span>");

      $("#units").on('click', function() {
        if ($(this).text() == "F") {
          $("#temp").html(Math.floor(tempCelsius) + " &deg;<span id='units'>C</span>");
        } else {
          $("#temp").html(Math.floor(tempFahrenheit) + " &deg;<span id='units'>F</span>");
        } 
      });

    });
  });
}

1 Answer 1

5

When you replace the html contents of the #temp div, you lose your event handler on the units div as well. Use event delegation instead. Assign the event on the body tag, but listen for events on the #units div.

Updated code:

  $("body").on('click', '#units',  function() {
    if ($(this).text() == "F") {
      $("#temp").html(Math.floor(tempCelsius) + " &deg;<span id='units'>C</span>");
    } else {
      $("#temp").html(Math.floor(tempFahrenheit) + " &deg;<span id='units'>F</span>");
    } 
  });

Working fork of your Codepen: https://codepen.io/anon/pen/AXzYzR?editors=0010

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.