Create Switch using HTML, CSS, and JavaScript Tutorial
In this tutorial, you will learn to create a Toggle Switch using HTML, CSS, and JavaScript. The tutorial aims to provide the students and new programmers with a reference for building a usable component for web applications using HTML, CSS, and JS from scratch. Here, a sample source code that demonstrates a simple toggle switch with functionality is provided. The complete source code zip file is also provided and is free to download.
What is Toggle Switch?
In web applications or web pages, the Toggle Switch simulates the on and off switch. It allows the user to choose between 2 options (on/off) and always has a default value. It is commonly used to provide immediate results and allow individuals to modify their choices as necessary. Enabling/Disabling the Dark Mode of the website is an example of a Toggle Switch.
How to create a Toggle Switch for websites?
Nowadays, some website developers are using pre-made templates or using CSS Frameworks such as Bootstrap Framework to build a website easily and faster. Almost all of the pre-made templates and CSS Frameworks come with toggle switches components so that developers will no longer bother to create one unless the design provided doesn't meet their needs. But if you wish to create your own custom-designed Toggle Switch, we can simply achieve this using some HTML elements, CSS pseudo-elements and properties for designing it, and some short lines of JavaScripts code.
The following list is the HTML elements and CSS pseudo-elements we can use to create a simple Toggle Switch.
- HTML Input Element [type="checkbox"]
- HTML Div Element
- CSS ::before pseudo-elements
- CSS ::after pseudo-elements
Example
To demonstrate how to build a Toggle Switch, I will be providing some snippets or scripts that will result in a simple web page that contains a Title and Toggle Switch component. The switch will be used to enable and disable the dark mode of the page interface.
Interface
The following script is the HTML script that contains the elements that are needed for the web page.
index.html
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="preconnect" href="https://fonts.googleapis.com">
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
- <link href="https://fonts.googleapis.com/css2?family=Mynerve&display=swap" rel="stylesheet">
- <link rel="stylesheet" href="style.css">
- </head>
- <body class="light">
- <hr width="50px">
- <!-- Toggle Switch Component -->
- <div class="custom-switch" data-true="Dark" data-false="Light" data-current="false">
- <input type="checkbox" class="custom-switch-input" checked="checked">
- </div>
- <!-- Toggle Switch Component -->
- </body>
- </html>
JavaScript
The following script is the JavaScript script that contains the code for enabling and disabling functionality of the page dark mode interface.
- const _cs_switch = document.querySelectorAll('.custom-switch')
- _cs_switch.forEach(cs_switch=>{
- const updateSwitch = function(){
- var current = cs_switch.dataset.current
- var on_label = cs_switch.dataset.true
- var off_label = cs_switch.dataset.false
- if(current === 'false'){
- cs_switch.querySelector('label').innerText = on_label;
- cs_switch.dataset.current = 'true'
- cs_switch.querySelector('input').setAttribute('checked', "checked")
- document.querySelectorAll('.light').forEach(el =>{
- el.classList.remove('light')
- el.classList.add('dark')
- })
- }else{
- cs_switch.querySelector('label').innerText = off_label;
- cs_switch.dataset.current = 'false'
- cs_switch.querySelector('input').dataset.checked = 'false'
- cs_switch.querySelector('input').removeAttribute('checked')
- document.querySelectorAll('.dark').forEach(el =>{
- el.classList.remove('dark')
- el.classList.add('light')
- })
- }
- }
- var default_is_checked = cs_switch.querySelector('input').getAttribute('checked') || false
- if(default_is_checked === "checked")
- updateSwitch();
- cs_switch.addEventListener('click', function(e){
- e.preventDefault()
- updateSwitch()
- })
- })
Default Design
By default, the application has only the following CSS code for the design of the web page which is the design of the toggle switch is not yet included.
- :root{
- --mynerve-font:'Mynerve', cursive;
- --light-color:#f9f9f9;
- --dark-color:#20262E;
- }
- h1{
- font-family: var(--mynerve-font)
- }
- .text-center{
- text-align: center;
- }
- .light{
- background-color: var(--light-color);
- color:#121212
- }
- .dark{
- background-color: var(--dark-color);
- color:#f7f7f7
- }
- body,
- html{
- height: 100%;
- width: 100%;
- }
- body{
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- margin: 0;
- }
Output
Creating the Toggle Switch
Next, using the following CSS script, the checkbox will be visually hidden on the web page. The switch block design will look like a pill with a label and a circle (representing the toggle lever) inside.
- /** Switch Default */
- .custom-switch {
- position: relative;
- border: 1px solid #d9d9d9;
- height: 30px;
- width: 130px;
- border-radius: 50px;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- transition: all .3s ease-in-out;
- -webkit-transition: all .3s ease-in-out;
- }
- .custom-switch *{
- cursor: pointer;
- }
- .custom-switch>label{
- font-weight: 600;
- color: #585858;
- padding: 0 15px;
- }
- .custom-switch>.custom-switch-input{
- position: absolute;
- visibility: hidden;
- }
- .custom-switch:before {
- content: "";
- position: absolute;
- width: calc(100% - 10px);
- height: calc(100% - 10px);
- left: 0px;
- top: 0px;
- border: 5px solid #f2f2f2;
- border-radius: 30px;
- z-index: -1;
- background: var(--light-color);
- }
- .custom-switch:after {
- content: "";
- position: absolute;
- top: calc(50% - 12px);
- height: 20px;
- width: 20px;
- border-radius: 100%;
- border: 2px solid #dbdbdb;
- background: #e5e5e5;
- transition: all .3s ease-in-out;
- -webkit-transition: all .3s ease-in-out;
- }
Creating the Toggle Switch Disabled Design
Next, let's create the design of the switch when it is disabled.
- /** Switch Disabled */
- .custom-switch[data-current="false"]{
- justify-content: end;
- }
- .custom-switch[data-current="false"]:after{
- left: 4px;
- }
Creating the Toggle Switch Enabled Design
Lastly, let's create the design of the toggle switch when enabled or toggled on using the following CSS code.
- /** Switch Enabled */
- .custom-switch[data-current="true"]{
- justify-content: start;
- color: #dddddd;
- }
- .custom-switch[data-current="true"]:after {
- left: calc(100% - 28px);
- background: #0c1c30;
- border-color: #4d5156;
- }
- .custom-switch[data-current="true"]>label {
- color: #dddddd;
- }
- .custom-switch[data-current="true"]:before {
- background: #121e2e;
- border-color: #262e38;
- }
There you go! You can now test the source code on your end and see if it works properly. The web page should like the following images when the Toggle Switch is Enabled/Disabled.
Toggle Switch Disabled
Toggle Switch Enabled
There you go! I have provided the complete source code zip file that I created for this tutorial demonstration. It is free to download on this site. The download button is located below this tutorial's content.
I hope this Create Switch using HTML, CSS, and JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.
Happy Coding =)
Add new comment
- 343 views