Skip to content Skip to sidebar Skip to footer

Disable Click Event Listener Of Square Temporally (color Picker Game)

I am working on RGB color picker game. the game generate random grid of 6 color squares and pick a random RGB color from these 6 color squares if the player choose the correct pick

Solution 1:

After searching for solution to my problem and with Alon Eitan's help I found a way to make click event listener for square work only once after trigger it.I just need to add another argument to addEventListener() which is {once:true}so it worked as expected.

also I found another method to hide square without changing its position on interface after wrong color square is clicked:

squares[i].style.visibility = "hidden"; 

code solution :

        squares[i].addEventListener("click",function(){
        // grab color of clicked squarevar clickedColor = this.style.backgroundColor;
        // compare color to pickedColorif(clickedColor === pickedColor){
            changeColors(clickedColor);
            h1.style.backgroundColor = clickedColor;
            resetBtn.textContent = "Play Again";
            messageDisplay.textContent = "Correct!";
        }
        else{
            // another way to hide the squarethis.style.visibility = "hidden"; 
            //this.style.backgroundColor = "#232323";
            messageDisplay.textContent = "Try Again!";
        }
       },{once: true});

some comments suggested to use removeEventListener()to disable square click event but in my case it's inefficient because I use anonymous function on addEventListener()for each square.

W3Schools mentions a Note on this case:

To remove event handlers, the function specified with the addEventListener() method must be an external function.

Anonymous functions, like "element.removeEventListener("event", function(){ myScript });" will not work.

Post a Comment for "Disable Click Event Listener Of Square Temporally (color Picker Game)"