Create a toggle switch with CSS and JavaScript

In this article we’ll see how to build a toggle switch using CSS and JavaScript. This type of component is very popular in web interfaces.

Let’s start from a simple HTML structure:

<input type="checkbox" class="toggle" name="toggle" value="1">

As a very first step, we need to wrap this checkbox element in a container with a specific class so that we can apply CSS styles.

function setToggleStructure() {
        const toggles = document.querySelectorAll('.toggle');
        if(toggles.length === 0) {
            return;
        }
        for(const toggle of toggles) {
            const parent = toggle.parentElement;
            const wrapper = document.createElement('div');
            wrapper.className = 'toggle-wrap';
            wrapper.innerHTML = toggle.outerHTML;
            parent.appendChild(wrapper);
            toggle.remove();
        }
    }

At this point, the DOM structure will look like this:

<div class="toggle-wrap">
   <input type="checkbox" class="toggle" name="toggle" value="1">
</div> 

With CSS, inside the container we’ll place the checkbox element in the foreground by setting its opacity to zero, and we’ll add a block created with generated content in the background whose width is half the width of .toggle-wrap. When the user checks or unchecks the checkbox, the .checked class will allow the block to move horizontally.

.toggle-wrap {
    display: inline-block;
    width: 3.2rem;
    height: 1.7rem;
    background-color: #eee;
    border-radius: 5px;
    position: relative;
    cursor: pointer;
}

.toggle-wrap:before {
    content: '';
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 50%;
    height: 100%;
    z-index: 1;
    background-color: #d41d6d;
    transition: all 400ms ease-in;
    transform: translateX(0);
    border-radius: 5px;
    opacity: 0.4;
}

.toggle-wrap.checked:before {
    transform: translateX(100%);
    opacity: 1;
}

.toggle-wrap .toggle {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
    z-index: 2;
}

Now with JavaScript we need to handle the change event on the checkbox so we can set the value property to the correct value and add or remove the .checked class on the container.

function handleToggleChange() {
        const toggles = document.querySelectorAll('.toggle');
        if(toggles.length === 0) {
            return;
        }
        for(const toggle of toggles) {
            toggle.addEventListener('change', () => {
                const parent = toggle.parentElement;
                if(toggle.checked) {
                    toggle.value = 1;
                } else {
                    toggle.value = 0;
                }
                parent.classList.toggle('checked');
            });
        }
    }

We can invoke our JavaScript code when the DOM is fully loaded:

document.addEventListener('DOMContentLoaded', () => {
        setToggleStructure();
        handleToggleChange();
});

Demo

CSS Toggle

Conclusion

A toggle switch is a perfect example of interaction between the presentational layer (CSS) and the behavioral layer (JavaScript) when building web interfaces.

Back to top