Examples with toggle in javaScript

Опубликовано: 26 Апрель 2026
на канале: Profu' de geogra'
16
0

1. Toggle with Boolean (using JavaScript)
Initially, isActive is set to false. let isActive = false;
When someone clicks the button, the toggleBackground function runs:
isActive = !isActive;
!isActive negates the current value.
If isActive is false, !isActive becomes true, so isActive is now true.
If isActive is true, !isActive becomes false, so isActive switches back to false.
This toggling effect allows the background color to change between light and dark each time the button is clicked.
In the previous example where we change the background color of the page, we could have used a boolean variable to track the background state. When toggling with a boolean, you change the state between true and false, and based on that state, you can apply changes, such as background color.

Phrase for this case:
"In the first example, we toggled the background color using a boolean (isActive), where clicking the button changes the isActive state between true and false, and depending on that state, we changed the background color to lightblue or white."

2. Toggle with Classes (using CSS class toggling)
In the second example, we used class toggling to change the background color by adding or removing a CSS class from the body element. The class active-background changes the background color to lightblue, while the default-background class sets the background color to white. This is done by toggling the class on and off each time the button is clicked.

Phrase for this case:
"In the second example, we toggled the background color by switching between two CSS classes (active-background and default-background). Each time the button is clicked, the active-background class is added or removed from the body element, changing the background color dynamically without needing to directly manipulate JavaScript variables."

This way, the difference between boolean toggling (changing internal state) and class toggling (changing styles visually via CSS) is highlighted in the context of the HTML code you were working with.