How to make my buttons work more than once in JavaScript?

41 views Asked by At

I'm working on the Odin Project Etch-a-Sketch. I've created 2 buttons Black and Rainbow and expect them to change the background colour of the squares inside the container each time I clicked the appropriate button but my buttons seem not to be working more than once.

Here is my goal: If the button Black is clicked I need the background of the squares to be black when the mouse is over the square. If the button Rainbow is clicked, I need the background of my squares to turn to random colours. The buttons work properly the first time they are clicked but if I click Black again the colour doesn't change back. What am I missing and how to fix it ?... Thanks.

let colourMode = toBlack;
const blackBtn = document.querySelector('#black');
const rainbowBtn = document.querySelector('#rainbow');

blackBtn.addEventListener('click', blackInk);
rainbowBtn.addEventListener('click', rainbowInk);

function toBlack() {
    return 'black';
}

function toRainbow() {
    const red = Math.floor(Math.random() * 256);
    const green = Math.floor(Math.random() * 256);
    const blue = Math.floor(Math.random() * 256);
    const cellBgColor = 'rgb(' + red + ',' + ' ' + green + ',' + ' ' + blue + ')';
    return cellBgColor;
}

function colour(e){
  e.target.style.backgroundColor = colorMode();
}

function blackInk() {
    const grid = Array.from(document.querySelectorAll('.cell'));
    const newGrid = Array.from(document.getElementsByClassName('.newCell'));

    grid.forEach(cell => cell.addEventListener('mouseover', colour)); 
    newGrid.forEach(newCell => newCell.addEventListener('mouseover', colour));
 }

function rainbowInk() {
    colorMode = toRainbow;
    const grid = Array.from(document.querySelectorAll('.cell'));
    const newGrid = Array.from(document.getElementsByClassName('.newCell'));
    grid.forEach(cell => cell.addEventListener('mouseover', colour));
    newGrid.forEach(newCell => newCell.addEventListener('mouseover', v));    
}
1

There are 1 answers

1
SANTHOSHKUMAR_S On

You need to update the blackInk() function to change the global colorMode variable value like this:

function blackInk() {
  colorMode = toBlack; // this line
    const grid = Array.from(document.querySelectorAll('.cell'));
    grid.forEach(cell => cell.addEventListener('mouseover', color)); 
    const newGrid = Array.from(document.getElementsByClassName('.newCell'));
    newGrid.forEach(newCell => newCell.addEventListener('mouseover', color));
 }