I am trying to make a toggle switch for the Local Weather project and I ran into an issue regarding javaScript/jQuery.
I have simplified my js code here and my html has only an h2 with .testClass class.
So I’d like the sum number to change whenever I click on sum1/sum2 text. While it works once (clicking on sum1 text changes to sum2), it doesn’t work the second time (else statement).
Also, if I remove the anchor tags from the sum1, sum2 variables and keep the text only, then target .testClass instead of .btnToggle, it seems to work but the click event is on the entire h2 .testClass
Is is common practice to add html tags with js? What am I missing here?
var sum1 = 32 + " <a href='#' class='btnToggle'> Sum 1</a>";
var sum2 = 88 + " <a href='#' class='btnToggle'> Sum 2</a>";
var toggle = true;
$(".testClass").html(sum1);
$(".btnToggle").click(function(){
if (toggle === true){
$(".testClass").html(sum2);
toggle = false;
} else{
$(".testClass").html(sum1);
toggle = true;
}
});
Thanks to anyone who has the patience to answer my question!