Hi guys, I was doing a project that required an ON/OFF switch. I kinda had a tough time creating a switch button. After finding my way around, I thought this migth be helpful for other people.
<div class="container">
<div class="toggle">
<div class="toggle-btn" onclick="Animatedtoggle()"></div>
</div>
<div class="text">OFF</div>
</div>
Create elements "toggle", "toggle-btn", and a "text" with OFF property. Create a button property inside the the toggle-btn div.
let toggle = document.querySelector(".toggle");
let text = document.querySelector(".text")
function Animatedtoggle(){
toggle.classList.toggle('active');
if(toggle.classList.contains('active')){
text.innerHTML = "ON";
}
else {
text.innerHTML = "OFF";
}
}
queryselect element ".toggel" to variable toggle.
do the same thing with "text".
classList toggle ('active') and then write a if loop for true "ON" and else "OFF".
Below is the full code template including stylesheet.
<!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">
<title>button</title>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<div class="container">
<div class="toggle">
<div class="toggle-btn" onclick="Animatedtoggle()"></div>
</div>
<div class="text">OFF</div>
</div>
<script>
let toggle = document.querySelector(".toggle");
let text = document.querySelector(".text")
function Animatedtoggle(){
toggle.classList.toggle('active');
if(toggle.classList.contains('active')){
text.innerHTML = "ON";
}
else {
text.innerHTML = "OFF";
}
}
</script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
position: relative;
background: aquamarine;
}
.container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
height: 50px;
display: flex;
align-items: center;
justify-content: center;
}
.container .toggle {
position: absolute;
top: 0;
left: 0;
width: 90px;
height: 40px;
background: rgb(8, 0, 15);
border-radius: 55px;
cursor: pointer;
transition: 0.3;
}
.container .toggle .toggle-btn {
position: absolute;
top: 5px;
left: 5px;
width: 40px;
height: 30px;
background: rgb(132, 115, 148);
border-radius: 25px;
transition: 0.3;
}
.container .toggle.active {
background:whitesmoke;
}
.container .toggle.active .toggle-btn {
left: 40px;
}
.text {
position: absolute;
left: 2.5cm;
font-size: 1.5rem;
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
margin-left: 8px;
}
Top comments (1)
Do you share the source code please