Add a toggle to your project

switch
Toggle switches are useful for mode switching, theme selection, or showing/hiding UI elements. This tutorial will show you how to add a toggle switch and read its state value.
Step 1. Create HTML file
Open a text editor and paste the following code. Save with .html extension. At the end of this tutorial I’ll explain how the script works for anyone interested.
document.getElementById(“Switch”).oninput = function() {
toggle state = this.checked? 1:0;
switchFunction();
};function switch function() {
console.log(“Toggle state:”,toggleState);
}
Step 2: Test File
Open the file in a browser and interact with the switch. The console will print the switching status.
Want to test HTML, CSS, JS online? use
Step 3: Use toggle states
You can now attach any behavior to toggleFunction(), depending on whether the switch is on (1) or off (0). For example, toggles are often used to switch themes, enable features, or show/hide parts of the UI.
Script description
style
style between Labels define the appearance of the toggle. The checkbox is hidden and the sliderBtn element becomes a visual switch. Rounded corners and transitions make switching feel smooth.
Body
Inside the body, we create a switch with a label. The input controls state, while sliderBtn is only used for visual effects. The toggle starts off but can be set to on by default by adding "checked" to the input.
script
JavaScript uses oninput to detect changes. After each user interaction, toggleState is updated to 0 or 1 and toggleFunction() is fired so you can handle the logic.
how do you use this
Here are some ideas:
• Light mode vs dark mode
• Mute/unmute
• Enable advanced settings
• Show/hide images or panels
• Activate filter or mode
Feel free to experiment and modify the switches to match your design. Thanks!


