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

Measuring the space between components

I am looking for a way to dynamically calculate distance on a canvas, similar to the example shown in the figure. I want to be able to drag the highlighted joints in order to adjust the span for calculating distances. Are there any plugins available for th ...

Transfer information via query or retrieve from storage in Vue

When considering sending a data variable to another component, is it more efficient to send it via query using a router or save the data in-store? Which method would be more optimal? router.replace({ name: 'routerName', query: { param ...

Show a modal with Jquery

Upon page load, I want to display a popup message. The popup is appearing correctly, but the close button in the bar is too big and doesn't fit properly. How can I adjust the size of the bar to accommodate the button? <script src="https://code.j ...

Access the OpenWeatherMap API to retrieve the weather forecast for a single time slot within a 5-day period

Utilizing the openweathermap api, I am retrieving a 5-day/3-hour forecast here. The API call provides multiple results for each day with data available every 3 hours. For the full JSON response, you can access it here. Please note that the API key is only ...

Tips for patiently waiting for a function that is filled with promises

Consider the following function: const getData = () => { foo() .then(result => { return result; }) .catch(error => { return error; }); }; Even though getData does not directly return a promise, it internally handles asynchro ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

The setState function in ReactJS seems to be failing to properly update the fields

I am having trouble resetting the value of my input type to empty after storing data from a controlled form element. The first method below is not working for me, even though I'm using setState to clear the input fields. Can someone help me understand ...

Pressing the reset button on the search box triggers a JQuery and HTML function

I am new to this, so bear with me. I've simplified my styling for easy pasting here, but the concepts still apply. I have a list of items, a working search field, and functioning filter buttons. What I want is for the filter buttons to reset to &apos ...

Unable to save the current light/dark mode preference to local storage

Being a beginner in JavaScript, I am currently working on implementing a simple light mode button for my website which defaults to dark mode. The transition between JS/CSS dark and light modes is seamless, giving the site an appealing look when switching t ...

Fetching data from a collection using Mongoose in Node JS

Currently working with MVC architecture. Seeking guidance on using the findOne({}) method in my loginController. I need to retrieve data from an existing collection, which already contains some information. My goal is simply to extract data from it. Apolo ...

What could be the reason behind jQuery replacing the entire span with .text?

I am dealing with the following HTML code snippet: <p><input id="revenue" type="text" value="100000" /><span id="howmuch"><a href="" class="ka_button small_button small_cherry" target="_self" style="opacity: 1; "><span>How Mu ...

Attempting to trigger the timer to begin counting down upon accessing the webpage

Take a look at this example I put together in a fiddle: https://jsfiddle.net/r5yj99bs/1/ I'm aiming to kickstart as soon as the page loads, while still providing the option to pause/resume. Is there a way to show the remaining time as '5 minute ...

Using jQuery's .live('click') method will only bind to the initial element found on the webpage

I developed a custom jQuery plugin that attaches to 8 different elements on a webpage. Within each element, I intended to utilize the .live() method to bind a click event to a link, triggering a form submission via ajax. However, I encountered an issue whe ...

Having trouble retrieving the data property from the parent component within the child component slot

I am facing an issue with my Vue components. I have a rad-list component and a rad-card component. In the rad-list component, I have placed a slot element where I intend to place instances of rad-card. The rad-card component needs to receive objects from t ...

The undead browser refuses to display a window upon attempting to open using the open function

tools first attempt Darwin 14.3.0 Darwin Kernel Version 14.3.0 io.js v1.8.1 zombie Version 4.0.7 released on April 10, 2015 second attempt Linux ubuntuG5 3.13.0-48-powerpc64-smp node.js v0.10.38 zombie Version 3.1.0 released on March 15, 2015 comman ...

Implementing a filter on retrieved data from an API in a React application

I'm retrieving information from this Api After fetching the data, I need to check if the gender is Male in order to display a Male Icon. How can I perform this check on the Api data and return some HTML data like an img tag or something to show the i ...

A method for arranging an array of nested objects based on the objects' names

Recently, I received a complex object from an API: let curr = { "base_currency_code": "EUR", "base_currency_name": "Euro", "amount": "10.0000", "updated_date": "2024 ...

The CSS media queries are failing to adjust the properties from 1024 to 768 as expected

Currently, I am working on implementing media queries to customize the color scheme for different screen sizes - particularly in 1024 view and 768 view. However, one issue that I encountered is that the properties defined for the 1024 view are being inheri ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

Ways to determine the specific content type within req.body?

Based on the information found at https://developer.mozilla.org/en-US/docs/Web/API/Request/Request, it is stated that the body of a request can be one of the following types: ArrayBuffer Blob formData JSON text I am wondering if there is a way ...