lundi 26 avril 2021

if statement isn't registering on 3rd button click

In the snippet below when the button is first clicked I want all of the divs to fade out except for the red one behind them all. On each subsequent click I want to set the opacity to 1 of the next div with higher stack order.

This works fine until the 3rd click - at which point 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 ( again )';
  }
  else if ( redStyle.opacity == 1 ) {
    greenStyle.opacity = 1;
    document.querySelector( 'button' ).innerHTML = 'click 2 ( again )';
  }  
  else if ( greenStyle.opacity == 1 ) {
    //This doesn't work
    blueStyle.opacity = 1;
    document.querySelector( 'button' ).innerHTML = 'click 3 ( 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( 0% );
  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>

click 3 never registers. The if statement for it checks if greenStyle.opacity == 1. Which it should be because greenStyles opacity was just set to 1 by the previous click.

In what way do I alter the code to register the 3rd click?

Aucun commentaire:

Enregistrer un commentaire