I hope you can help me with my weather app. I am doing things in stages really, and instead of going all out putting all the data points on my page, I am working with one data point (forecasted temperature) and a basic toggle switch to try and get the switch between units to work. Link to CodePent is below:
I am at the point now where I am writing the Javascript and jQuery, and have had some difficulty getting it to work with clean code. When I wrote the Celsius code out it worked fine, but when I added the “.click” function nothing displayed when the page loaded until the button was clicked. I have tried so many ways to get around it but I feel like I may be missing something.
What I have done at the moment is loaded the the initial call first to the api for Celsius data (which displays content), and then I have added an if statement to toggle between Celsius and Fahrenheit. Is there a better way of doing this? If so what would kind of method would you suggest? This is so I have something to go on when doing more research into cleaning up my code and writing it better.
Thanks! Button has now changed location, it was only there for testing purposes ;).
I have amended the code to put everything into functions. One question I do have (if anyone can answer it) is, is it possible for me to make a call in a function, and then amend the elements outside of the function some how?
And I have it again but for fahrenheit (so it is duplicated, but the current_observation.temp_c and current_observation.feelslike_c is now f instead of c). Would it be possible to have the full call in the function, and then have the document.getElementById statements outside of the function? This is so I make one API call and bundle in all of the JSON data grabbing into one function, and then I am free to amend the elements in one bunch.
Hi GraemenElliot,
Yes, you can do with one function call instead of 2. I forked your pen and change it for Celsius. You can do the changes for F in the similar way.
You pass argument unit into the function call. Unit is either “c” or “f”. The way the if statement is written at the moment: it will default to “f” if “c” is not passed as an argument to the function call.
I had to change variables inside {} from “let” to “var” to preserve value outside of {}.
Just to correct myself:
I fused condApiCallC and condApiCallF into one function call: condApiCall
You can do the same for forecastApiCallC and forecastApiCallF
You are the only person on the internet who has actually made me cry haha (don’t worry, they are tears of joy!)! Thanks so much for the help. I was up until 3am Sunday morning trying to figure this out before asking on here (I tried so hard to figure it out on my own). That looks so much better, and something I will definitely remember now. Thank you!