Javascript: How to change class and CSS when value is zero

Issue

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')
        };

      })
    });

Solution

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!!

Answered By – ps2708

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.