So I've been trying to make this switch, it's simple in my head. stating a variable "num" equaling 1 to begin with, setting an "if" or "while" statement for when "num" is equal to 2, the background color of a certain div will change from white to yellow and back in .5 second intervals. My problem I THINK is that I can't seem to change the global variable. I've changed it to 2, and the loop worked, but when it's 1 and I try to use the button to change to 2, nothing happnes! Here's the JS I have so far:
var num = 1;
document.getElementById("numberDisplay").innerHTML = num;
if (num == 2) {
var flash = setInterval(timer, 1000);
function timer() {
document.getElementById("colorChanger").style.backgroundColor = "yellow";
setTimeout(white, 500);
function white() {
document.getElementById("colorChanger").style.backgroundColor = "white";
}
}
} else {
document.getElementById("colorChanger").style.backgroundColor = "white";
document.getElementById("numberDisplay").innerHTML = num;
}
document.getElementById("buttonOne").onclick=function(){num = 1;}
document.getElementById("buttonTwo").onclick=function(){num = 2;}
edit: 1/30/2018 12:25pm Really appreciate the help guys! A friend of mine actually gave me some advice, that was using window.onload and event timers! Here's what I came up with:
var num = 1;
window.onload = function(){
var button1 = document.getElementById("buttonOne")
var button2 = document.getElementById("buttonTwo")
button1.addEventListener("click",function(){
num = 2;
})
button2.addEventListener("click",function(){
num = 1;
})
setInterval(checkNum, 1000);
}
function checkNum() {
if (num == 2) {
document.getElementById("buttonOne").style.backgroundColor = "#ccccb3";
document.getElementById("buttonTwo").style.backgroundColor = "white";
document.getElementById("lightChanger").style.backgroundColor = "yellow";
setTimeout(grey, 500);
function grey() {
document.getElementById("lightChanger").style.backgroundColor = "grey";
}
} else {
document.getElementById("lightChanger").style.backgroundColor = "grey";
document.getElementById("buttonOne").style.backgroundColor = "white";
document.getElementById("buttonTwo").style.backgroundColor = "#ccccb3";
}
}