Why is my button not working?


Hi coders,

I’m working on the weather app project and I can’t get my button to switch between Celsius and Fahrenheit. I’m not worried about the symbols at the moment just making the numbers work. Would anyone be able to diagnose the problem for me?



You can’t set a click event for an element that doesn’t exist. Right now you’re creating a click event targeting “#fahrenheit” but there are no elements on the page that match that. Instead, you need to bind your click event to the button, and then do logic inside the callback to see if it’s set to fahrenheit or celsius.


One more thing. You should replace your $.html() with $.text().

Also $.prop() with $.attr()


As mentioned above, it isn’t possible to bind a click handler to an element that doesn’t exist yet. Since the button has id=“celsius” on page load, this code works:


But this code is ignored:


You will need to unbind and then re-attach the click handler after every ID change. You also need to update the value of temp for your calculation since it will change with every click.

This could work:

function givesFahrenheit() {
  temp = $(".temp").text() * 9 / 5 + 32;
  $(".button").attr("id", "fahrenheit");

function givesCelsius() {
  temp = ($(".temp").text() - 32) * 5 / 9;
  $(".button").attr("id", "celsius");


But…a better solution, IMO, is to use jQuery’s .data() API: https://api.jquery.com/jquery.data/

var celsius = $(".temp").text();

$(".temp").data({ // store the fahrenheit, celsius, and unit in a .data() object
  fahrenheit: celsius * 9 / 5 + 32 + " ° F",
  celsius: celsius + " ° C",
  currentUnit: "celsius"

$("#celsius").on("click", function() {
  $temperature = $(".temp").data();
  $(".button").text($temperature.currentUnit); // change button text to the unit that will be displayed when clicked

  if ($temperature.currentUnit === "celsius") { // change the currentUnit value in the data() object
    $temperature.currentUnit = "fahrenheit";
  } else {
    $temperature.currentUnit = "celsius";
  $(".temp").html($temperature[$temperature.currentUnit]); // update the temperature on the page

Here is a codepen I created to help out with this:



Wow this is excellent. I haven’t come across .data before, so many gaps in my knowledge. o_O Thank you for doing that it is greatly appreciated.


That makes a lot of sense, thanks!