The condition is not being recognized after clicking the third button

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?

Answer №1

It seems that the issue lies in the fact that the second else if statement is never reached due to the fact that redStyle.opacity remains at a value of 1 and the third check will only be performed if the preceding if statements return false. To resolve this, you can introduce an additional condition check for greenStyle.opacity before evaluating redStyle.opacity.

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 ( greenStyle.opacity == 1 ) {
    //This doesn't work
    blueStyle.opacity = 1;
    document.querySelector( 'button' ).innerHTML = 'click 3 ( again )';
  }    
  else if ( redStyle.opacity == 1 ) {
    greenStyle.opacity = 1;
    document.querySelector( 'button' ).innerHTML = 'click 2 ( 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatically Scrolling Div According to its Content

Struggling to figure out how to make a parent div automatically scroll based on its child's content. I have a menu that expands when clicked and needs to scroll if the height of the child exceeds that of the parent. This is the HTML for the menu wra ...

How to selectively disable buttons in a group using React

I am working with an array of data const projectTypeValues = [ { name: 'Hour', value: 'hour'}, { name: 'Day', value: 'day'}, { name: 'Session', value: 'session'}, { name: 'project', valu ...

Tips on displaying each element of an array in a unique format within a React component

I am working on creating a component that will display data in boxes. Each set of constant data should be placed within a div for organization. Currently, I have a Box component that is responsible for displaying the data. The Tutorial component receives ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

The props in Vue 3 are not functioning as expected in child components even after being bound correctly, resulting in undefined values in the child component

Exploring the realms of Vue and Laravel, I find myself in new territory. As the parent element, I fetch items from the database successfully. Now, the task at hand is to pass this data to the child component. <template> <div class="todoList ...

Is there a way to set a higher priority over the "!important" rule on my website?

I'm encountering a strange issue with my website. I have been working on this website and am looking to change the color of the main menu hover links from white to orange. Here is the CSS related to that section: .darkheader .navigation > ul > ...

JavaScript's ability to call object properties at multiple levels allows for complex data

My approach involves using mongodb in conjunction with ajax calls for data retrieval. However, I have encountered an issue where the properties needed to generate HTML from JavaScript objects are sometimes missing. Consider this ajax call: $.ajax({ ...

Encountering a proxy error while attempting to create an account or log in, with no network

Embarking on my first web development journey, I utilized React-Redux to craft a React.js application within the client folder. For the backend code, I employed Node.js and MongoDb as my database. This project represents a significant milestone in my lear ...

Transform the string response in a websocket message into JSON format

When receiving a websocket message, I often encounter a response in the form of a string like this: odds.1:[{"id":1,"marketType":10,"name":"Double chance","status":"HandedOver","specifiers":"","Outcomes":[]},{"id":2,"marketType":11,"name":"Draw no bet", ...

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

Is it Possible to Alter the Title Attribute in AngularJS with ng-class?

My website currently displays an image that updates based on the user's selection from a dropdown menu. The title of the image is set to "test", but I need it to display a different message depending on which image is being shown. Can this be achieved ...

Phaser 3 shows images as vibrant green squares

In my project, I have two scenes: Loading and Menu. In the loading scene, I load images with the intention of displaying them in the menu. Here is the code for the Loading scene: import { CTS } from './../CTS.js'; import { MenuScene } from &apo ...

How to assign a value in an HTML element using AngularJS

Currently, I am utilizing Angular JS to iterate through a portion of a scope that is initially a JSON array. My objective is to verify the existence of a specific value in that array. If the value exists, then certain actions should be taken. The code bel ...

Create a table within the B-Col element that automatically adjusts its size to match the column width using Vue-Bootstrap

Within my Vue component, I have the following code snippet: <b-modal ...> <b-row> <b-col sm="12"> <table > <tr v-for=... :key="key"> <td><strong>{{ key }}: </str ...

Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue. var b = 44; function test(){ var a = b = 2; } However, the following code works without any problems: var b = 44; function test(){ var a; var b = 2; } The global ...

`In NodeJS, facing a challenge with implementing a many-to-many relationship using Sequelize's

I'm in the process of setting up many-to-many relationships between roles and accesses. The `roles` table will contain a list of roles (admin, developer, etc...) and the `accesses` table will have a list of permissions (Create Project, Create Site, De ...

What value does the "left" property default to?

When attempting to change the 'left: 0' property to 'left:none', I found that it did not work. Other properties such as margin and padding do work when overwritten. I aim to find a solution for this problem without altering the origina ...

Testing the updated version 18 of Create React APP index.js using Jest

Previously, I had this index.js file created for React version <= 17. import React from 'react'; import ReactDOM from 'react-dom'; import App from './views/App'; import reportWebVitals from './reportWebVitals'; im ...

What steps should I take to insert a divider in a dropdown menu?

I am attempting to enhance my dropdown menu by incorporating a separator using the following code: <li class='divider'></li> Below is my HTML code with the separator included: <ul class="dropdown-menu dropdown-menu-right" id="ul ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...