Recently, I was working on a toggle-style button setup for the CodePen Challenge. I wanted to give the button a 3D appearance, so I set up a little JavaScript code that would use onclick to do this.
var on = true
const green = document.getElementById('on')
const red = document.getElementById('off')
var greenOn = function() {
if (on == false) {
green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15) inset'
red.style.boxShadow = 'none'
var on = true;
}
}
var redOn = function() {
if (on == true) {
green.style.boxShadow = 'none'
red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15) inset'
var on = false
}
}
Here’s the code all nice and bundled into a code snippet.
var on = true
const green = document.getElementById('on')
const red = document.getElementById('off')
var greenOn = function() {
if (on == false) {
green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15) inset'
red.style.boxShadow = 'none'
var on = true;
}
}
var redOn = function() {
if (on == true) {
green.style.boxShadow = 'none'
red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15) inset'
var on = false
}
}
.on {
border-radius: 5px;
background-color: lime;
padding: 50px;
border: none;
}
.off {
border-radius: 5px;
background-color: red;
padding: 50px;
border: none;
}
.switch {
padding: 0;
margin: 0;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="switch">
<button class="on" id="on" onclick="greenOn()"></button>
<button class="off" onclick="redOn()" id="off"></button>
</div>
</body>
</html>
When I do it, nothing happens. Can someone help me fix it?
>Solution :
There are two problems with your code
-
You are setting
var on = true
andvar on = false
in your function even after you have declared it globally, you are making a new variable on in function scope, that is whyon
is not changing.
change it toon = false
andon = true
to respective functions -
The vlaue you applied to
box-shadow
proprty is not a valid value. Add a valid property value to see the changes
var on = true;
const green = document.getElementById('on');
const red = document.getElementById('off');
var greenOn = function() {
if (!on) {
green.style.boxShadow = 'inset -3px 3px 13px 0px rgba(0,0,0,0.15)';
red.style.boxShadow = 'none';
on = true;
}
}
var redOn = function() {
if (on) {
green.style.boxShadow = 'none';
red.style.boxShadow = '-3px 3px 13px 0px rgba(0,0,0,0.15)';
on = false;
}
}
.on {
border-radius: 5px;
background-color: lime;
padding: 50px;
border: none;
}
.off {
border-radius: 5px;
background-color: red;
padding: 50px;
border: none;
}
.switch {
padding: 0;
margin: 0;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="switch">
<button class="on" id="on" onclick="greenOn()"></button>
<button class="off" onclick="redOn()" id="off"></button>
</div>
</body>
</html>