I’m working on my weather App. The API requests are working fine and all content is displayed properly as far as I can tell. However I wanted an option for the user to be able to toggle between Celsius and Fahrenheit…I’ve written code for this which doesn’t work, and I’m struggling to understand why (please see my CodePen below).
I’m guessing it has something to do with appending a new element ID using JQuery and then trying to make a JQuery object variable from an element ID which doesn’t actually exist in the HTML? I don’t know. Would really love an explanation !
I think it can’t find #temp because of $temp.replaceWith(). You’re replacing the <h2 id="temp"> with a plain <h2>. How about using $temp.html() instead? You’ll have to tweak the arguments passed to it a bit though.
Instead of changing the DOM id with each click and looking for unique F and C ids, what about a single DOM id who’s content changes conditionally on each click? I forked and reworked your app a bit: codepen link. The onClick function checks the value of units & updates it and the inner html of <span id="units"></span> on each click. The relevant toggle code:
$units.on("click", function() {
if (units === "C") {
$temp.html(temperatureF.toFixed(1));
units = "F";
$units.html("F");
} else {
$temp.html(temperatureC.toFixed(1));
units = "C";
$units.html("C");
}
});
Thanks belcurv, that’s a far more elegant solution. Naming and separating the callbacks makes for much nicer reading also!
I’m still curious as to why my original code didn’t work though. Do you know?