Switching Celsius to Fahrenheit, help

Switching Celsius to Fahrenheit, help
0.0 0

#1

I’m really struggling with the unit change, I thought to writte a simple if/else and just apply the formula to change those units but it’s not working properly.

First things first, I’m telling the api to send me the data in metric units:

var apiCall = “https://crossorigin.me/http://api.openweathermap.org/data/
2.5/weather?lat=”+latitude+"&lon="+longitude+"&appid=XXXXXXXX&units=metric";

Then I wrotte this, it works because it changes the Celsius to Fahrenheit, but it does so directly, without any clicks involved, and I cannot return it to metric by clicking on “metric” either. How can I make it so the clicks work?

$.getJSON(apiCall, function(val) {

/* If user clicks on the div with the “imperial” class, then apply the math formula
to change Celsius to Fahrenheit on the current value, which is Celsius. */

if($(".imperial").click()){
$("#mainTemp").text(“Current temperature: " + (val.main.temp *(9/5) + 32 )).append(” °F");

// If the user clicks on metric, just display the temp as it is.

} else if($(".metric").click()){
$("#mainTemp").text(“Current temperature: " + (val.main.temp)).append(” °D");

// Else, just display it as it is.

} else {
$("#mainTemp").text(“Current temperature: " + (val.main.temp)).append(” °D"); }


#2

Most likely you are using jQuery.

If that’s the case, you need to change your code a bit

$(document).ready(function(){
    //some other code
    
    //following line should be placed above click functions 
    //to ensure that it doesn't overwrite changes made inside click functions
    $("#mainTemp").text("Current temperature: " + (val.main.temp)).append(" °D");
    
    $(".imperial").click(function(){
        $("#mainTemp").text("Current temperature: " + (val.main.temp *(9/5) + 32 )).append(" °F");
    }); 
    $(".metric").click(function(){
        $("#mainTemp").text("Current temperature: " + (val.main.temp)).append(" °D");
    });
    
    // some other code
});

You need to make sure that VAL is visible here.


#3

Sorry I forgot to edit my post as someone pointed out my mistake of not adding a callback function after the click. So this works as expected now:

$(".imperial").click(function(){
$("#mainTemp").text(“Current temperature: " + (val.main.temp * (9/5) + 32 )).append(” °F");

Thanks for your reply.