Search code examples
javascriptloopsclickaddeventlistenerminesweeper

button changes color even if it's already assigned


I have this problem: whenever I click on the div, I want to add background color. Forever. But background changes even if I click more (like a loop). How to set background color forever?

const blocks = document.querySelectorAll('.game div');
const liveNumber = document.querySelector('.lives-num');
let lives = 1;


function letTheGameBegin(e, r) {
    const rand = Math.floor(Math.random() * 100);
    if (rand < 40) {
        e.target.style.backgroundColor = 'green';
    } else if (rand < 60) {
        e.target.style.backgroundColor = 'yellow';
        lives++;
    } else if (rand < 90) {
        e.target.style.backgroundColor = 'red';
        lives--;
    } else {
        e.target.style.backgroundColor = 'white';
    }
    liveNumber.innerHTML = lives;
    if (lives === 0) {
        //document.querySelector('.game-over').style.display = 'flex';
    }
}

blocks.forEach(block => block.addEventListener('click', letTheGameBegin));

Solution

  • I think you mean you only want to run the JS once per div.

    Try this example and see if its what you need: jsfiddle

    function letTheGameBegin(e, r) {
        const rand = Math.floor(Math.random() * 100);
        if(!e.target.style.backgroundColor){
            if (rand < 40) {
                e.target.style.backgroundColor = 'green';
            } else if (rand < 60) {
                e.target.style.backgroundColor = 'yellow';
                lives++;
            } else if (rand < 90) {
                e.target.style.backgroundColor = 'red';
                lives--;
            } else {
                e.target.style.backgroundColor = 'white';
            }
            liveNumber.innerHTML = lives;
            if (lives === 0) {
                //document.querySelector('.game-over').style.display = 'flex';
            }
        }
    }