I have a div that I need to change color based on a javascript if-statement. The check is being made by pressing the green divbox and if the background is set to green, the box should change to black background.
Note! I do not wish to use another solution. I am just looking for understanding why this particular solution does not work.
If you activate the lowest positioned function that does work without button click, you need to inactivate the first function.
function changeColorOnReloadIfGreen() {
var x = document.getElementById('box-1');
if (x.style.backgroundColor == 'green') {
x.style.backgroundColor = 'black';
}
}
/*********************************************************/
/*
Just for reference, activating below
that changes box-1 to black works (without if-statement).
*/
/*********************************************************/
/*
var x = document.getElementById('box-1')
x.style.backgroundColor = 'black';
*/
.box-1 {
background-color: green;
width: 100px;
height: 100px;
margin: 30px 0px 0px 30px;
}
<div id="box-1" class="box-1" onclick="changeColorOnReloadIfGreen()"></div>