Toggle button in Weather App not working properly

I am working on Weather App and i have created a button to toggle between Celcius and Fahranheit Temperature. I am using a counter and if that counter is even the fahranheit is displayed else celcius.
But unfortunately the button works only once that is it changes the initial celcius temp to fahranheit then it dose not work for fahranheit to celcius. Can anyone see whats the problem??
This is the code:-

Not an expert yet but I think the problem is that you create a new button in your js code and when you do that, the on click function won’t apply to it anymore. Had this problem with my current project, the delegate() is used for this but I couldn’t get it work (didn’t spend too much time trying) so my recommendation is to create the button in html, let JS handle its inner html and use toggle() to make it appear and disappear if you wish.

Below is a section of your code where you try to add the click handler to the button which was dynamically created:


@IamFlok was correct that you need to delegate the binding to the the element change. You can do that using .on as follows:


          far = 9 / 5 * json.main.temp + 32;

          $("#main-temp").on("click", "#change", function() {

The above code was part of the following if statement’s code block for when it evaluated to true:

if (c % 2 == 0) {

You had an else block of code which also creates a button. I did not spend too much time trying to figure out the rest of your code, but was curious when the c variable would ever not have the value 2 for the else block of code to run?

thanks @IamFlok and @rmdawson71 for the help. It is working now.
@rmdawson71 …I did not get your doubt about “c” variable. It is basically a counter that is initialized with a value of 2 and is incremented on each click. And if value of c is even then if will run otherwise else.

I read your code again, I now I understand what you are doing with the c variable.