When the button is clicked for the first time in the code snippet below, all divs except for the red one should fade out. With each subsequent click, the opacity of the next div with a higher stack order should be set to 1
.
Everything works fine until the 3rd click - after that, nothing happens:
document.querySelector( 'button' ).addEventListener( 'click', button );
let black = document.querySelector( '.black' ),
blue = document.querySelector( '.blue' ),
green = document.querySelector( '.green' ),
red = document.querySelector( '.red' );
black.style.opacity = 1; blue.style.opacity = 1;
green.style.opacity = 1; red.style.opacity = 1;
function button() {
let blackStyle = black.style,
blueStyle = blue.style,
greenStyle = green.style,
redStyle = red.style;
if( blackStyle.opacity == 1 ) {
blackStyle.opacity = 0;
blueStyle.opacity = 0;
greenStyle.opacity = 0;
redStyle.opacity = 1;
document.querySelector( 'button' ).innerHTML = 'click 1 registered ( again )';
}
else if ( redStyle.opacity == 1 ) {
greenStyle.opacity = 1;
document.querySelector( 'button' ).innerHTML = 'click 2 registered ( again )';
}
else if ( greenStyle.opacity == 1 ) {
//This doesn't work
blueStyle.opacity = 1;
document.querySelector( 'button' ).innerHTML = 'click 3 registered ( again )';
}
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body {
display: flex;
justify-content: center;
align-items: center;
}
div, button {
position: absolute;
border-radius: 10rem;
width: 10rem;
height: 10rem;
background-color: #e23;
transition-property: opacity;
transition-duration: 0.25s;
}
.green { transform: scale( 0.8 ); background-color: #3e5; }
.blue { transform: scale( 0.5 ); background-color: #2af; }
.black { transform: scale( 0.1 ); background-color: #222; }
button {
transform: translateX( -25% );
left: 12.5%;
border-style: none;
border-radius: 1rem;
width: auto;
height: auto;
padding: 0.75rem;
background-color: #000;
color: #fff;
cursor: pointer;
}
button:hover { background-color: #444; }
<div class='red'></div>
<div class='green'></div>
<div class='blue'></div>
<div class='black'></div>
<button>click here ( again )</button>
The third click never registers.
The if statement for it checks if greenStyle.opacity == 1
. It should be true because greenStyles opacity was just set to 1 by the previous click.
What changes should I make to the code to register the 3rd click?