Onclick function not working for weather project, please help!

I am trying to get the Celsius symbol to switch to the Fahrenheit and back when it is clicked. It doesn’t seem to matter where I place the function or where I define the variables. Any suggestions would be appreciated!

Here is the javascript, and the problem area has the ## highlights. I also had to delete a few lines of url and variables so I could post this:

$( document ).ready(function(){
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
      var lat = "lat=" + position.coords.latitude;
      var lon = "lon=" + position.coords.longitude;
      weather(lat, lon);
## // I've tried putting these variable declarations in many places and different ways.  
## var x;
## var array = ["C", "F"];
## var unit = array[0];

##   //This onclick function never works, no matter where I put it. I tried inside the weather function in various places, after the( document).ready, and before it.
## $("#symbol").on("click", function() {
##   if (x==0) {
##     x = 1
##   } else {
##     x = 0
##   };  
##  });

function weather (lat, lon) {
$.getJSON(url, function (data) {
  if (unit == "C") {
  $("#temp").html(data.main.temp.toFixed()+ " ");
  } else {
    $("#temp").html((data.main.temp*9/5+32).toFixed()+ " ");
  var html = "";
   html += "<img src = '" + data.weather[0].icon + "' >"; 

Post your example with better formatting or in codepen/jsfiddle/similar. It hurts my snowflake eyes that are so used to nice formatting :slight_smile:

You could test if your event is firing just logging something to the console first and only when that works, then calling your logic.

Right now, as is, x is never assigned. Also I think you should assign unit as array[x], not array[0].

Thank you, I will post the codepen when I can get to it. I have tried array[x] and assigning x to be 0 and nothing works.

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


Thanks for all the help–I resolved the issue. I put all the variables and functions that depend on the JSON data inside the getJSON request. I still don’t understand callbacks and other possible solutions though!