Playground

Switch

A simple toggle switch element to enable or disable an option.

+ Tailwind and Alpine

Copied!
<div x-data="{ switchOn: false }" class="flex items-center justify-center space-x-2">
    <input id="thisId" type="checkbox" name="switch" class="hidden" :checked="switchOn">

    <button 
        x-ref="switchButton"
        type="button" 
        @click="switchOn = ! switchOn"
        :class="switchOn ? 'bg-blue-600' : 'bg-neutral-200'" 
        class="relative inline-flex h-6 py-0.5 ml-4 focus:outline-none rounded-full w-10"
        x-cloak>
        <span :class="switchOn ? 'translate-x-[18px]' : 'translate-x-0.5'" class="w-5 h-5 duration-200 ease-in-out bg-white rounded-full shadow-md"></span>
    </button>

    <label @click="$refs.switchButton.click(); $refs.switchButton.focus()" :id="$id('switch')" 
        :class="{ 'text-blue-600': switchOn, 'text-gray-400': ! switchOn }"
        class="text-sm select-none"
        x-cloak>
        Enable Feature
    </label>
</div>

Data

Below you will find the data properties available in the x-data attribute of this element.


Property and Description
switchOn
A boolean value that will toggle the switch on or off (active or inactive)

More Examples

Below you will find more Switch examples you may wish to use in your projects.


Copied!
<div x-data="{ switchOn: false }" class="flex items-center justify-center space-x-2">
    <input id="thisId" type="checkbox" name="switch" class="hidden" :checked="switchOn">

    <button 
        x-ref="switchButton"
        type="button" 
        @click="switchOn = ! switchOn"
        :class="switchOn ? 'bg-neutral-900' : 'bg-neutral-200'" 
        class="relative inline-flex h-4 py-0.5 ml-4 rounded-full focus:outline-none w-6"
        x-cloak>
        <span :class="switchOn ? 'translate-x-[10px]' : 'translate-x-0.5'" class="w-3 h-3 duration-200 ease-in-out bg-white rounded-full shadow-md"></span>
    </button>

    <label @click="$refs.switchButton.click(); $refs.switchButton.focus()" :id="$id('switch')" 
        :class="{ 'text-neutral-900': switchOn, 'text-gray-400': ! switchOn }"
        class="text-xs font-medium select-none"
        x-cloak>
        Enable Feature
    </label>
</div>

A project by DevDojo