JSFiddle - React, Tailwind, and code Playground
HTML
<button id="button" type="submit">
Click me
</button>
<p id="second" class="print2">
Hello World
</p>
CSS
.print1 {
color: red;
font-size: 24px;
}
.print2 {
color: blue;
font-size: 12px;
}
JavaScript
let counter = 0; //establishing the counter
button.addEventListener("click", function() { //adding an event listener means the function isn't just firing once every time the button is pressed. Instead, it is continually running.
let button = document.querySelector("#button"); //get the button
let print1 = 'Goodbye Foo'; //set the content as a string for the first print state
let print2 = 'Hello World'; //set the content as a string for the second print state
let printer = document.getElementById('second'); //where the content will print
if (counter % 2 == 0) { //if the remainder of the counter divided by 2 is 0, then:
printer.innerHTML = print1; //change the inner html to the first string
printer.classList.replace('print2', 'print1'); //and toggle between these two classes
} else { //otherwise, if the remainder of the counter does not equal 0 when divided by 2, then:
printer.innerHTML = print2; //print the second string
printer.classList.replace('print1', 'print2'); //and toggle between these two css classes
}
if (counter >= 9) { //then, to make sure the counter doesn't get insanely high, if the counter is ever equa
counter = 0;
} else {
counter += 1;
}
});