{
    "id": "bhaskar/rocker-switch-with-click-sound",
    "kind": "component",
    "title": "Rocker Switch with Click Sound",
    "summary": "A clean 3D OFF/ON rocker switch with a crisp mechanical click sound. Real checkbox underneath, keyboard-ready, any ON colour and size.",
    "author": "Admin",
    "stars": 0,
    "url": "https://ownlyplans.com/bhaskar/rocker-switch-with-click-sound/",
    "stack": [
        "CSS",
        "HTML",
        "JavaScript",
        "React"
    ],
    "tools": [
        "claude-code",
        "cursor",
        "lovable"
    ],
    "difficulty": "beginner",
    "license": "mit",
    "version": "1.1",
    "overview": "A minimal on/off rocker with depth: the paddle tips over in 3D, the active side lights up, and it makes a crisp mechanical click (a bright snap, a short woody thock and a tiny spring tick, slightly higher when it turns on). The sound is made in code with the Web Audio API, so there are no audio files to load.\r\n\r\nUnderneath it is a real checkbox with role=\"switch\", so it works in forms (name and value), with Space and Tab, and with screen readers, and it shows a focus ring for keyboard users. Change the ON colour with --rk-on, the size with --rk-size (the whole switch scales from it), the labels in the HTML, and the volume, or turn the sound off with data-sound=\"off\" on the label. Class names are prefixed (rk-) so they never clash with your own styles.\r\n\r\nBased on the open-source switch by Richard Tsang (r7chardgh) on Uiverse.io, customised by OwnlyPlans with the sound, accessibility, options and a React version.\r\n\r\nMIT License\r\n\r\nCopyright (c) 2023 Richard Tsang (r7chardgh), original switch design on Uiverse.io\r\nCopyright (c) 2026 OwnlyPlans, click sound, accessibility, options and React version\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
    "steps": [],
    "files": [],
    "install": "npx shadcn@latest add https://ownlyplans.com/r/bhaskar/rocker-switch-with-click-sound.json",
    "how_to_use": "Use the component code (html, css, js, or react) directly, or run the install command.",
    "component": {
        "category": "Toggles and inputs",
        "html": "<!--\nMIT License\n\nCopyright (c) 2023 Richard Tsang (r7chardgh), original switch design on Uiverse.io\nCopyright (c) 2026 OwnlyPlans, click sound, accessibility, options and React version\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n-->\n<label class=\"rk-switch\">\n  <input class=\"rk-cb\" type=\"checkbox\" role=\"switch\" aria-label=\"Power\" name=\"power\">\n  <span class=\"rk-toggle\">\n    <span class=\"rk-left\">off</span>\n    <span class=\"rk-right\">on</span>\n  </span>\n</label>",
        "css": "/*\n * MIT License\n *\n * Copyright (c) 2023 Richard Tsang (r7chardgh), original switch design on Uiverse.io\n * Copyright (c) 2026 OwnlyPlans, click sound, accessibility, options and React version\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n/* The switch - the box around the slider */\n.rk-switch{--rk-size:17px;--rk-on:#487bdb;--rk-body:#373737;font-size:var(--rk-size);position:relative;display:inline-block;width:5em;height:2.5em;user-select:none}\n/* Hide default HTML checkbox (it stays focusable for the keyboard) */\n.rk-switch .rk-cb{opacity:0;width:0;height:0}\n/* The slider */\n.rk-toggle{position:absolute;cursor:pointer;width:100%;height:100%;background-color:var(--rk-body);border-radius:.1em;transition:.4s;text-transform:uppercase;font-weight:700;overflow:hidden;\n font-family:system-ui,-apple-system,\"Segoe UI\",sans-serif;\n box-shadow:-.3em 0 0 0 var(--rk-body),-.3em .3em 0 0 var(--rk-body),.3em 0 0 0 var(--rk-body),.3em .3em 0 0 var(--rk-body),0 .3em 0 0 var(--rk-body)}\n.rk-toggle>.rk-left{position:absolute;display:flex;width:50%;height:88%;background-color:#f3f3f3;color:var(--rk-body);left:0;bottom:0;align-items:center;justify-content:center;\n transform-origin:right;transform:rotateX(10deg);transform-style:preserve-3d;transition:all 150ms}\n.rk-left::before{position:absolute;content:\"\";width:100%;height:100%;background-color:#cecece;transform-origin:center left;transform:rotateY(90deg)}\n.rk-left::after{position:absolute;content:\"\";width:100%;height:100%;background-color:#707070;transform-origin:center bottom;transform:rotateX(90deg)}\n.rk-toggle>.rk-right{position:absolute;display:flex;width:50%;height:88%;background-color:#f3f3f3;color:#cecece;right:1px;bottom:0;align-items:center;justify-content:center;\n transform-origin:left;transform:rotateX(10deg) rotateY(-45deg);transform-style:preserve-3d;transition:all 150ms}\n.rk-right::before{position:absolute;content:\"\";width:100%;height:100%;background-color:#cecece;transform-origin:center right;transform:rotateY(-90deg)}\n.rk-right::after{position:absolute;content:\"\";width:100%;height:100%;background-color:#707070;transform-origin:center bottom;transform:rotateX(90deg)}\n.rk-switch .rk-cb:checked+.rk-toggle>.rk-left{transform:rotateX(10deg) rotateY(45deg);color:#cecece}\n.rk-switch .rk-cb:checked+.rk-toggle>.rk-right{transform:rotateX(10deg) rotateY(0deg);color:var(--rk-on)}\n/* OwnlyPlans additions */\n.rk-switch .rk-cb:focus-visible+.rk-toggle{outline:2px solid var(--rk-on);outline-offset:.45em}\n.rk-switch .rk-cb:disabled+.rk-toggle{opacity:.5;cursor:not-allowed}\n@media (prefers-reduced-motion:reduce){.rk-toggle>.rk-left,.rk-toggle>.rk-right{transition:none}}",
        "js": "/*\n * MIT License\n *\n * Copyright (c) 2023 Richard Tsang (r7chardgh), original switch design on Uiverse.io\n * Copyright (c) 2026 OwnlyPlans, click sound, accessibility, options and React version\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nlet rkAudio = null;\nfunction rockerClick(on, volume = 0.6) {\n  try {\n    const AC = window.AudioContext || window.webkitAudioContext;\n    if (!AC) return;\n    rkAudio = rkAudio || new AC();\n    const ac = rkAudio, t = ac.currentTime + 0.002, out = ac.createGain();\n    out.gain.value = volume; out.connect(ac.destination);\n    const len = Math.floor(ac.sampleRate * 0.03), buf = ac.createBuffer(1, len, ac.sampleRate), d = buf.getChannelData(0);\n    for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / len, 6);\n    const snap = (at, freq, gain) => {\n      const src = ac.createBufferSource(), bp = ac.createBiquadFilter(), g = ac.createGain();\n      bp.type = 'bandpass'; bp.frequency.value = freq; bp.Q.value = 1.4; g.gain.value = gain;\n      src.buffer = buf; src.connect(bp); bp.connect(g); g.connect(out); src.start(at);\n    };\n    snap(t, on ? 3600 : 2600, 0.9);\n    snap(t + 0.011, on ? 5200 : 4200, 0.25);\n    const body = ac.createOscillator(), bg = ac.createGain();\n    body.type = 'sine'; body.frequency.setValueAtTime(on ? 210 : 150, t); body.frequency.exponentialRampToValueAtTime(on ? 120 : 85, t + 0.05);\n    bg.gain.setValueAtTime(0.0001, t); bg.gain.exponentialRampToValueAtTime(0.7, t + 0.002); bg.gain.exponentialRampToValueAtTime(0.0001, t + 0.07);\n    body.connect(bg); bg.connect(out); body.start(t); body.stop(t + 0.08);\n  } catch (e) { /* no audio available: stay silent */ }\n}\n/* Every .rk-switch on the page clicks when it changes. */\ndocument.querySelectorAll('.rk-switch').forEach((sw) => {\n  const cb = sw.querySelector('.rk-cb');\n  cb.addEventListener('change', () => {\n    if (sw.dataset.sound !== 'off') rockerClick(cb.checked, parseFloat(sw.dataset.volume || '0.6'));\n    sw.dispatchEvent(new CustomEvent('rk:change', { bubbles: true, detail: { checked: cb.checked, name: cb.name } }));\n  });\n});",
        "react": "/*\n * MIT License\n *\n * Copyright (c) 2023 Richard Tsang (r7chardgh), original switch design on Uiverse.io\n * Copyright (c) 2026 OwnlyPlans, click sound, accessibility, options and React version\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\"use client\";\nimport { useState, type CSSProperties } from \"react\";\n\nconst css = `/* The switch - the box around the slider */\n.rk-switch{--rk-size:17px;--rk-on:#487bdb;--rk-body:#373737;font-size:var(--rk-size);position:relative;display:inline-block;width:5em;height:2.5em;user-select:none}\n/* Hide default HTML checkbox (it stays focusable for the keyboard) */\n.rk-switch .rk-cb{opacity:0;width:0;height:0}\n/* The slider */\n.rk-toggle{position:absolute;cursor:pointer;width:100%;height:100%;background-color:var(--rk-body);border-radius:.1em;transition:.4s;text-transform:uppercase;font-weight:700;overflow:hidden;\n font-family:system-ui,-apple-system,\"Segoe UI\",sans-serif;\n box-shadow:-.3em 0 0 0 var(--rk-body),-.3em .3em 0 0 var(--rk-body),.3em 0 0 0 var(--rk-body),.3em .3em 0 0 var(--rk-body),0 .3em 0 0 var(--rk-body)}\n.rk-toggle>.rk-left{position:absolute;display:flex;width:50%;height:88%;background-color:#f3f3f3;color:var(--rk-body);left:0;bottom:0;align-items:center;justify-content:center;\n transform-origin:right;transform:rotateX(10deg);transform-style:preserve-3d;transition:all 150ms}\n.rk-left::before{position:absolute;content:\"\";width:100%;height:100%;background-color:#cecece;transform-origin:center left;transform:rotateY(90deg)}\n.rk-left::after{position:absolute;content:\"\";width:100%;height:100%;background-color:#707070;transform-origin:center bottom;transform:rotateX(90deg)}\n.rk-toggle>.rk-right{position:absolute;display:flex;width:50%;height:88%;background-color:#f3f3f3;color:#cecece;right:1px;bottom:0;align-items:center;justify-content:center;\n transform-origin:left;transform:rotateX(10deg) rotateY(-45deg);transform-style:preserve-3d;transition:all 150ms}\n.rk-right::before{position:absolute;content:\"\";width:100%;height:100%;background-color:#cecece;transform-origin:center right;transform:rotateY(-90deg)}\n.rk-right::after{position:absolute;content:\"\";width:100%;height:100%;background-color:#707070;transform-origin:center bottom;transform:rotateX(90deg)}\n.rk-switch .rk-cb:checked+.rk-toggle>.rk-left{transform:rotateX(10deg) rotateY(45deg);color:#cecece}\n.rk-switch .rk-cb:checked+.rk-toggle>.rk-right{transform:rotateX(10deg) rotateY(0deg);color:var(--rk-on)}\n/* OwnlyPlans additions */\n.rk-switch .rk-cb:focus-visible+.rk-toggle{outline:2px solid var(--rk-on);outline-offset:.45em}\n.rk-switch .rk-cb:disabled+.rk-toggle{opacity:.5;cursor:not-allowed}\n@media (prefers-reduced-motion:reduce){.rk-toggle>.rk-left,.rk-toggle>.rk-right{transition:none}}`;\n\nlet rkAudio: AudioContext | null = null;\n/** Plays the rocker click. Call it from a user action (browsers need a gesture). */\nexport function rockerClick(on: boolean, volume = 0.6) {\n  try {\n    const AC = window.AudioContext || (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n    if (!AC) return;\n    rkAudio = rkAudio || new AC();\n    const ac = rkAudio, t = ac.currentTime + 0.002, out = ac.createGain();\n    out.gain.value = volume; out.connect(ac.destination);\n    const len = Math.floor(ac.sampleRate * 0.03), buf = ac.createBuffer(1, len, ac.sampleRate), d = buf.getChannelData(0);\n    for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * Math.pow(1 - i / len, 6);\n    const snap = (at: number, freq: number, gain: number) => {\n      const src = ac.createBufferSource(), bp = ac.createBiquadFilter(), g = ac.createGain();\n      bp.type = 'bandpass'; bp.frequency.value = freq; bp.Q.value = 1.4; g.gain.value = gain;\n      src.buffer = buf; src.connect(bp); bp.connect(g); g.connect(out); src.start(at);\n    };\n    snap(t, on ? 3600 : 2600, 0.9);\n    snap(t + 0.011, on ? 5200 : 4200, 0.25);\n    const body = ac.createOscillator(), bg = ac.createGain();\n    body.type = 'sine'; body.frequency.setValueAtTime(on ? 210 : 150, t); body.frequency.exponentialRampToValueAtTime(on ? 120 : 85, t + 0.05);\n    bg.gain.setValueAtTime(0.0001, t); bg.gain.exponentialRampToValueAtTime(0.7, t + 0.002); bg.gain.exponentialRampToValueAtTime(0.0001, t + 0.07);\n    body.connect(bg); bg.connect(out); body.start(t); body.stop(t + 0.08);\n  } catch (e) { /* no audio available: stay silent */ }\n}\n\nexport function RockerSwitch({\n  checked,\n  defaultChecked = false,\n  onChange,\n  offLabel = \"off\",\n  onLabel = \"on\",\n  size = 17,\n  onColor = \"#487bdb\",\n  sound = true,\n  volume = 0.6,\n  name,\n  disabled,\n  \"aria-label\": ariaLabel = \"Switch\",\n}: {\n  checked?: boolean;\n  defaultChecked?: boolean;\n  onChange?: (checked: boolean) => void;\n  offLabel?: string;\n  onLabel?: string;\n  /** Font size in px; the whole switch scales from it (default 17). */\n  size?: number;\n  onColor?: string;\n  sound?: boolean;\n  /** 0 to 1 */\n  volume?: number;\n  name?: string;\n  disabled?: boolean;\n  \"aria-label\"?: string;\n}) {\n  const [inner, setInner] = useState(defaultChecked);\n  const on = checked ?? inner;\n  return (\n    <label className=\"rk-switch\" style={{ \"--rk-size\": `${size}px`, \"--rk-on\": onColor } as CSSProperties}>\n      <style>{css}</style>\n      <input\n        className=\"rk-cb\"\n        type=\"checkbox\"\n        role=\"switch\"\n        aria-label={ariaLabel}\n        name={name}\n        disabled={disabled}\n        checked={on}\n        onChange={(e) => {\n          const next = e.target.checked;\n          if (checked === undefined) setInner(next);\n          if (sound) rockerClick(next, volume);\n          onChange?.(next);\n        }}\n      />\n      <span className=\"rk-toggle\">\n        <span className=\"rk-left\">{offLabel}</span>\n        <span className=\"rk-right\">{onLabel}</span>\n      </span>\n    </label>\n  );\n}\n\n/* Usage:\n   <RockerSwitch aria-label=\"Power\" onChange={setPower} />\n   <RockerSwitch size={24} onColor=\"#16a34a\" offLabel=\"no\" onLabel=\"yes\" volume={0.4} name=\"newsletter\" />\n*/",
        "dependencies": [],
        "install": "npx shadcn@latest add https://ownlyplans.com/r/bhaskar/rocker-switch-with-click-sound.json",
        "licence_notice": "MIT License\n\nCopyright (c) 2023 Richard Tsang (r7chardgh), original switch design on Uiverse.io\nCopyright (c) 2026 OwnlyPlans, click sound, accessibility, options and React version\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
    }
}