Home > Back-end >  Javascript: How to change class and CSS when value is zero
Javascript: How to change class and CSS when value is zero

Time:04-24

I have 9 boxes in my html.

There is a value, id called 'lifepoint'.

There is a mouse-click function: click once & decrease one life point. This code is completed.

function decrementlife() {
        var element = document.getElementById('lifepoint');
        var value = element.innerHTML;
    
        --value;
        console.log(value);
        document.getElementById('lifepoint').innerHTML = value;
        if(value <= 0) { alert("Game Over!")};
    }

Also, there is a css style, called 'crackbox'.

.crackbox {
    position: relative;
    background: linear-gradient(0deg, black, rgb(120, 120, 120));
    width: 12vh;
    height: 12vh;
    border-radius: 30%;
    margin: 5px;
}

I want to change all box class from 'box' to 'crackbox' if life point is zero. Therefore, all box style can be 'crackbox'.

The below code is fail...

$(document).ready(function () {
      $(".box").each(function() {
        document.getElementById('lifepoint').innerHTML = value;
        if(value <= 0) { 
          ".box".toggleClass('crackbox')
        };

      })
    });

CodePudding user response:

Instead of using document ready, call another function from decrement life if the value turns 0. I am writing the code for your help.

function decrementlife() {
    var element = document.getElementById('lifepoint');
    var value = element.innerHTML;

    --value;
    console.log(value);
    document.getElementById('lifepoint').innerHTML = value;
    if(value <= 0) { changeClass(); alert("Game Over!")};
}

function changeClass(){
   $('.box').addClass('crackbox').removeClass('box');
}

Hope, it helps!!

CodePudding user response:

The simplest way would be to use querySelectorAll and loop through the elements:

for(let i = 0, list = document.querySelectorAll(".box"); i < list.length; i  )
{
  list[i].classList.toggle('crackbox');
}

Or shorter ES6 version:

[...document.querySelectorAll(".box")].forEach(el => el.classList.toggle('crackbox'))
  • Related