Toggle button in Weather App not working properly

Toggle button in Weather App not working properly
0

#1

Hello!
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:- https://codepen.io/karanatwal/pen/YxxVbZ


#2

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.


#3

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

       $("#main-temp").html(tem);
       
       far=9/5*(json.main.temp)+32;
       
       $("#change").on("click",function(){

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

          $("#main-temp").html(tem);

          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?


#4

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.


#5

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