Toggling classes with jQuery

Toggling classes with jQuery
0

#1

Currently working on building the basic functionalities of the weather project. I’m trying to create a button that toggles between showing the temperature in Fahrenheit and in Celsius. I wrote the below jQuery code to do calculations as necessary based on whether button class is declared “tempInC” or “tempInF”:

$(".tempInC").html(currentTempinC + String.fromCharCode(176) + “C”);
$(".tempInF").html(currentTempinF + String.fromCharCode(176) + “F”);

This works when I manually change the button’s class in HTML. However, when I try to toggle the class with jQuery, it doesn’t work. Here’s my jQuery code:

$(".tempInC").click(function(){
$(this).toggleClass(“tempInF”);
});
$(".tempInF").click(function(){
$(this).toggleClass(“tempInC”);
});

As a test, I wrote CSS code that assigns tempInC to green text and tempInF to blue text. The toggle actually works for this (the button text turns green or blue when I click on it), but it still doesn’t change the number and C or F symbol itself. Does toggling only work for CSS then?

Here’s my codepen:
https://codepen.io/alissaw/live/NvMrjN

Thanks for any clarification you can provide!


#2

When you click the button and the class is “tempInC”, it changes the class to “tempInF” which changes the text to green. When you click on the button and the class is “tempInF”, it changes the class to “tempInC” which changes the text to green.

You need to have your button click event also change the html content of the button to the desired temperature information. The JQuery toggleClass function only changes the CSS class.


#3

Got it. Thanks so much!