Sling Academy
Home/JavaScript/Creating a Toggle Switch from Scratch in JavaScript

Creating a Toggle Switch from Scratch in JavaScript

Last updated: December 12, 2024

Creating a toggle switch in a web application is a common task that enhances the user experience by allowing intuitive on/off interactions. This tutorial will walk you through building a simple, functional toggle switch using HTML, CSS, and JavaScript.

Step 1: Setting Up the HTML

We'll start with a basic HTML structure. In this example, the toggle switch consists of a checkbox input wrapped inside a label, which provides the ability to toggle its state by clicking anywhere on the switch.

<!-- HTML -->
<label class="toggle-switch">
    <input type="checkbox">
    <span class="slider"></span>
</label>

The <input> element of type checkbox acts as the toggle switch trigger, and it is styled using CSS to appear like a switch slider.

Step 2: Styling with CSS

Once the structure is ready, we need to style the toggle switch with CSS. This involves making the checkbox not visible and instead designing the <span> to look like a toggle switch.

/* CSS */
.toggle-switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
}

.slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    transition: .4s;
}

input:checked + .slider {
    background-color: #2196F3;
}

input:checked + .slider:before {
    transform: translateX(26px);
}

In the above code, the .toggle-switch class sets the dimensions of the switch, making it fell as if it were a part of the page. The .slider and its :before pseudo-element handle the appearance of the switch, creating the slider button effect. When the checkbox is checked, the + selector moves the circle using CSS transitions, giving it a smooth sliding motion.

Step 3: Adding Functionality with JavaScript

The toggle switch functionality primarily relies on the checkbox of HTML. However, you may want to run some function when the switch is toggled. This is possible using JavaScript event listeners.

// JavaScript
const toggleSwitch = document.querySelector('.toggle-switch input');

toggleSwitch.addEventListener('change', function() {
  if (this.checked) {
    console.log('Toggle Switch is ON');
    // Add your 'on' logic here
  } else {
    console.log('Toggle Switch is OFF');
    // Add your 'off' logic here
  }
});

This script listens for a change event on the checkbox input. When the toggle is switched on or off, the event triggers, logging the state to the console (or executing any JavaScript logic you wish to add).

Advanced Tips

Enhancing the toggle switch can also involve accessibility improvements and further personalization:

  • Accessibility: Always ensure that your toggle switch is accessible. You can achieve this by providing appropriate aria-label or aria-labelledby attributes to give assistive technologies additional context.
  • Customization: You can easily modify the size, colors, and styles of your toggle switch by altering the CSS values or adding classes that apply specific themes on runtime via JavaScript.

By following the above steps, you have created a functional and stylized toggle switch. This kind of feature is frequently used in web applications, mobile sites, and single-page apps, offering an elegant solution for binary decisions. Remember, implementation might vary slightly depending on your specific requirements or front-end frameworks in use. Happy coding!

Next Article: Simple SPA Routing: Switching Content Areas with the JavaScript DOM

Previous Article: Editing Text Content Inline with JavaScript DOM

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration