Toggle switch problem help please (weather app) [SOLVED]


I finished my weather app a little while ago, but have gone back to it to try and fix a bug. I’m stumped.

The bug is that the temp and speed units switches stop working on a search (keystroke or go button) or a locate via the locate button. They then start to work again if I perform either of those actions.

Things i’ve tried:

  • I tried wrapping the toggle setup in a function and calling it when page is fully populated. Currently its in a code block with the rest of the data parse called populate().

  • Moving the switch setup into the doc ready section at the top (whilst wrapped in function) with the other buttons

  • Removing doc ready altogether

  • Changing the lines within the switch setup to pure jquery as it is a bit of a mix of jquery and js.

None of these things worked so I didn’t commit, what you see on github is as it was. I’m in the process of writing a load of console logs into the app so will commit that instead when done.

Current js on github, the switch set up is right at the bottom.

Many thanks if you can find the time to take a look for me.



Hey, I think I found the problem, haven’t tried the fix though.

You are assigning the click handler every time you run populate(). So, if populate() is called a second time, it will toggle the button twice (because it runs the click handler twice). If you try searching again (populate() will run for the third time) you will see that the toggle buttons work, because they get toggled three times (so effectively they are just toggled once).

You should be able to fix this, by changing this:
$('#temp-toggle').click(function() {
$('#temp-toggle').unbind().click(function() {

And of course the same for the $("#speed-toggle")

1 Like

That has indeed fixed it,

I had seen the click was registering a few times when I logged it (in fact the number accumilated after every click) so I knew it would be something like this although I hadn’t figured out why, I didn’t realise I was piling on the click function like that until I saw the word unbind in your answer and it instantly clicked! So thanks for the unbind() tip, I’ll rememebr that one.

Shows up my bad formating too. I might have a look and see where I can fit that button setup without piling the function like that - such a practice can’t be good practice.

Thanks very much mr Gitter

1 Like