JavaScript toggle switch: Interactive state change

JavaScript Event Handling: Exercise-7 with Solution

Write a JavaScript program to implement a toggle switch that changes its state when clicked.

Sample Solution:

HTML and JavaScript Code:

<!DOCTYPE html>
    .toggle {
      display: inline-block;
      width: 60px;
      height: 34px;
      position: relative;
      border-radius: 34px;
      background-color: #ccd;
      cursor: pointer;
      transition: background-color 0.3s;

    .toggle::before {
      content: "";
      position: absolute;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background-color: #fff;
      top: 4px;
      left: 4px;
      transition: transform 0.3s;

    .toggle.on {
      background-color: #66bb6a;

    .toggle.on::before {
      transform: translateX(26px);
  <div class="toggle"></div>

    const toggle = document.querySelector('.toggle');

    toggle.addEventListener('click', () => {

Sample Output:

JavaScript toggle switch: Interactive state change.
JavaScript toggle switch: Interactive state change.

Note: Executed on JS Bin


In the above exercise,

We have a <div> element with the class toggle that represents a toggle switch. The switch has an initial state of "off" (default) defined by the .toggle class. When the switch is toggled on, the .on class is added to the toggle element, changing its appearance.

CSS styles define the toggle switch's appearance and behavior. The .toggle class sets the dimensions, position, border radius, and transition properties. The .toggle::before pseudo-element creates the circular handle of the switch. The .toggle.on class changes the background color of the switch when it is toggled on. The .toggle.on::before class transforms the handle to the "on" position.

The JavaScript code attaches a click event listener to the toggle element. When the toggle switch is clicked, the event listener toggles the .on class on the toggle element using the classList.toggle() method. This changes the state of the switch and triggers the corresponding CSS styles for the on or off state.


Flowchart: JavaScript toggle switch: Interactive state change.

Live Demo:

See the Pen javascript-event-handling-exercise-7 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Event Handling Exercises Previous: JavaScript Drag-and-Drop: Reorder items in a list.
Event Handling Exercises Next: JavaScript progress bar: Dynamic task completion tracking.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.