Weather App - celsius and fahrenheit toggle

Hi guys :slight_smile:

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 !

Thanks advance! :slight_smile:

Your click events are working. I tried inserting a console.log in one of them and it gets called.

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.

Ohhhhh yes of course! Haha thank you. I’ll give that a bush and report back

So I’ve managed to get it to toggle to Fahrenheit but can’t get it to toggle back…really can’t figure this one out! Any ideas?

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") {
    units = "F";
  } else {
    units = "C";
1 Like

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?

I’m still curious as to why my original code didn’t work though. Do you know?

Do you have a copy of the original? I don’t remember exactly how it looked.

Sorry, I’ve changed it and can’t remember for the life of me how it was before! Nevermind, thank you for your help :slight_smile: