Hudson Taylor
Hudson Taylor

Reputation: 1162

Javascript Toggle HTML

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>");
        } 
      });

    });
  });
}

Upvotes: 0

Views: 103

Answers (1)

HaukurHaf
HaukurHaf

Reputation: 13806

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

Upvotes: 5

Related Questions