Home > Net >  Can't make a simple If Else statement work
Can't make a simple If Else statement work

Time:12-10

Hello I'm making a simple counter that is counting to 3 every time i click the button. The counter works just fine, because I can see how he changes in the console. The problem is, my JS isn't affecting the CSS. When I delete the else statements and leave only one, this is the one that is working.

CSS. note: The strongAttackBtn and strongAttackBtnLoading are in the same div.

.strongAttackBtn {
    height: 50px;
    width: 150px;

    color: black;
    font-weight: 800;
}
.strongAttackBtnLoading {
    position: absolute;
    height: 50px;
    width: 150px;
    background-color: rgba(0,0,0,0.5);
}

JS

const strongAttackBtnLoading = document.querySelector('.strongAttackBtnLoading');    
const strongAttackBtn = document.querySelector('.strongAttackBtn');
let strongAttackCounter = 0;

if (strongAttackCounter === 3) {
    strongAttackBtnLoading.style.width = '150px';
} else if (strongAttackCounter === 2) {
    strongAttackBtnLoading.style.width = '100px';
} else if (strongAttackCounter === 1) {
    strongAttackBtnLoading.style.width = '50px';
} else if (strongAttackCounter === 0) {
    strongAttackBtnLoading.style.width = '0px';
}

strongAttackBtn.addEventListener('click', function(){
  strongAttackCounter  ;
})

CodePudding user response:

Try this code.

You have to assign CSS to both DIVs and put your if statement code in the addEventListener click function.

const strongAttackBtn = document.querySelector('.strongAttackBtn');
const strongAttackBtnLoading =document.querySelector('.strongAttackBtnLoading');
var strongAttackCounter = 0;
strongAttackBtn.addEventListener('click', function(){
  strongAttackCounter  ;
  
  if (strongAttackCounter === 3) {
    strongAttackCounter=0; // set it to zero again;
    
    strongAttackBtnLoading.style.width = '150px';
    strongAttackBtn.style.width = '150px';
    
  } else if (strongAttackCounter === 2) {
  
      strongAttackBtnLoading.style.width = '100px';
      strongAttackBtn.style.width = '100px';
      
  } else if (strongAttackCounter === 1) {
  
      strongAttackBtnLoading.style.width = '50px';
      strongAttackBtn.style.width = '50px';
      
  } else if (strongAttackCounter === 0) {
  
      strongAttackBtnLoading.style.width = '0px';
      strongAttackBtn.style.width = '0px';
      
  }
})
.strongAttackBtn {
    height: 50px;
    width: 150px;

    color: black;
    font-weight: 800;
}
.strongAttackBtnLoading {
    position: absolute;
    height: 50px;
    width: 150px;
    background-color: rgba(0,0,0,0.5);
}
<div ><input  type="button" value="strongAttackBtn"></div>

  • Related