How can I use toggleClass to switch between Fahrenheit and Celsius on my $('p') tag when clicked

Why won't the toggleClass() work on the $('p') that is suppose to switch between Fahrenheit to Celsius and back to Fahrenheit and so forth as many times as users want?

Link to Code: http://codepen.io/duel_drawer8/pen/bpoozL

My full code if you can't see link:

//Our ID key for weather app
var appID = "&APPID=f74316dbe7442f12d602b1cae1a5172b";

var city;
var state;
var fahrenheit = "&units=imperial";
var temp;

//using a geo-location API to get city and state info of current user
$.getJSON('http://ip-api.com/json/?callback=?', function(data) {
  city = data.city;
  state = data.regionName;
  getWeather(city, state);
});

//using weather API and outputting results into our HTML
function getWeather(city, state) {
  var api = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + state + "" + fahrenheit + "" + appID;

$.ajax({
url: api,
dataType: 'json',
success: function(data) {
  temp = data.main.temp;
  $('h3').text(city + "," + state);
  $('p').html(temp + '&deg F');

  }
 });
}

$('p').on('click', function(){
    $('p').text(changeTemp(temp));
    $('p').toggleClass(changeTemp(temp));
});

function changeTemp(temp){
   var cel = (temp - 32) * 5/9;
   return cel;
};

Answers 1

  • Add a class to the p tag to decide whether you should insert the celsius or fahrenheit on the next click.

    Then toggle the class on each click.

    Since you have the temperature as global variable you don't need to pass it to the function.

    Create different functions for either adding the fahrenheit temp or calculating the celsius temp.

    $('p').on('click', function(){
      $('p').toggleClass('celcius');
      $('p').toggleClass('fahrenheit');
    
      if ($(this).hasClass('celcius')) {
        $('p').text(setFahrenheit());
        return;
      }
    
      $('p').text(setCelcius());
    });
    
    function setCelcius(){
      var cel = (temp - 32) * 5/9;
      return cel + "? C";
    };
    
    function setFahrenheit(){
      return temp + "? F";
    };
    

    Here is my codepen-fork

    Or another approach - maybe cleaner approach:

    • calculating both temps in the ajax success and storing it in an object
    • adding a data attribute to the p tag to decide which value to show next
    • on click - decide which value to show based on data attribute and switch the data attribute

    Here is another codepen-fork


Related Articles