@bartonyoung Ok, I’m going to just give you the answer - but you have to promise you’ll analyze it to figure out why your code wasn’t working and why this is better. I’ll tell you what to remove, then give you working code to replace it with.
Take these lines and delete them:
//variable for temp in Fahrenheit
var temperature_F = Math.round(json.main.temp) + '<a class="unitSwitch">' + '°F' + '</a>';
//variable for temp in Celcius
var temperature_C = Math.round((json.main.temp - 32) / 1.8) + '<a class="unitSwitch">' + '°C' + '</a>'
Then delete these lines:
$tempBox.append('<div class="temp">' + temperature_F +'</div>',
'<div class="clouds">' + clouds +'</div>',
'<img src='+icon+' alt="" class="img-thumbnail">'
);
Then delete these lines:
//ALLOWS USER TO TOGGLE BETWEEN FARENHEIT AND CELCIUS
$(".unitSwitch").click(function(){
if ( $(this).text() === '°F' ) {
$('.temp').html(temperature_C);
}
else {
$('.temp').html(temperature_F);
}
});
Then, where the above lines that you just deleted were, add all of this:
var temp = Math.round(json.main.temp); // gets temp from API
$tempBox.append(
'<div class="temp">' + temp +'</div>', // Displays temp in F on load
'<a class="unitSwitch">' + '°F' + '</a>', // Defines the unit for the callback function below to grab on to
'<div class="clouds">' + clouds +'</div>',
'<img src='+icon+' alt="" class="img-thumbnail">'
);
$(".unitSwitch").click(function(){
if ( $(this).text() === '°F' ) {
$('.temp').html(Math.round((json.main.temp - 32) / 1.8)); // Replaces F with temp converted to C
$('.unitSwitch').html('°C')
} else {
$('.temp').html(Math.round(json.main.temp)); // Replaces C temp with original temp by calling the API again
$('.unitSwitch').html('°F')
}
});
The code placement might not be the best, and you might have to work with the styling a bit to make everything look right, but if you deleted all the lines I pointed out, and replaced with the above, the code should work (works well when I do it in Chrome).
Just make sure you take a look at your previous code and see why it’s not working. Your code is a bit funky, but it looks like it should work as is, but I think the problem is having those 2 elements assigned to variables. This is essentially doing the same thing, but in a less roundabout way. Let me know if you have success with this and if you have any other questions, I will do my best to answer what I can.
This could also be done by calling the API only once when the page loads, rather than getting the temp every time you click, but it would require a slightly different approach. This should be a good solution for the way you currently have things set up.