I want to using javascript to make a light switch.
When the background color is:
"white" => turn on
"black" => turn off
Question: My code can turn off the light, but I don't know how to turn it on.
I have a idea to the last, but it dosen't work. How to fix it?
Here is my code.
HTML
<!DOCTYPE HTML>
<html lang="en">
<head>
<mate charset="utf-8" />
<title>light Switch</title>
<link rel="stylesheet" href="lightSwitch.css" />
</head>
<body>
<!--
<a href="javascript:void(0)" id="lightOn">turn on</a>
</br>
<a href="javascript:void(0)" id="lightOff">turn off</a>
</br>
-->
<a href="javascript:void(0)" id="lightSwitch">The switch</a>
<script src="lightSwitch.js"></script>
</body>
</html>
CSS
body{
background-color: white;
margin: 0;
padding: 0;
}
#lightSwitch{
width: 300px;
height: 25px;
text-align: center;
border: 1px solid black;
padding: 5px;
text-decoration: none;
position: absolute;
top: 50%;
left: 50%;
margin: -15px 0 0 -152.5px;
}
javascript
function lightSwitch(){
var light = document.getElementById("lightSwitch");
var BGcolor = document.body.style.backgroundColor;
if (BGcolor != "black"){
light.innerHTML = "The light is open! Click here to close.";
light.onclick = function(){
document.body.style.backgroundColor = "Black";
light.innerHTML = "The light is close! Click here to open.";
}
}
}
lightSwitch();
I have a idea, look:
function lightSwitch(){
var light = document.getElementById("lightSwitch");
var BGcolor = document.body.style.backgroundColor;
if (BGcolor != "black"){
light.innerHTML = "The light is open! Click here to close.";
light.onclick = function(){
document.body.style.backgroundColor = "Black";
light.innerHTML = "The light is close! Click here to open.";
}else{
light.onclick = function(){
document.body.style.backgroundColor = "white";
}
}
}
}
lightSwitch();