Home > front end >  Clicking on an image not working as intended
Clicking on an image not working as intended

Time:01-09

I made a game where you need to click the image on the left side of the screen that you do not see on the opposite side to get to the next level. For some reason, when you click any image on the left side you still go to the next level. When you click the wrong image it should say game over. Right now it only does that when the whitespace is clicked. Any tips?

enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Matching Game</title>
    <style>
      img {
        position: absolute;
     }  
     div {
       position: absolute;
       width: 500px;
       height: 500px;
     }
     #rightSide {
       left: 500px;
       border-left: 1px solid;
     }
   </style>
</head>
<body onl oad="generateFaces()">
<h1>Matching Game</h1>
<p>Click on the extra smiling face on the left.</p>

<div id="leftSide"></div>
<div id="rightSide"></div>

<script >
    let numberOfFaces = 5;
    const theLeftSide = document.querySelector("#leftSide");
    const theRightSide = document.querySelector("#rightSide");

    function generateFaces() {
        for (let i = 0; i < numberOfFaces; i  ) {
            let face = document.createElement("img");
            face.src = 'images/smile.png';

            const randomTop = Math.floor(Math.random() * 400)   1;
            const randomLeft = Math.floor(Math.random() * 400)   1;

            face.style.top = randomTop   'px';
            face.style.left = randomLeft   'px';

            theLeftSide.appendChild(face);

            theLeftSide.lastChild.addEventListener('click', nextLevel);
            document.body.addEventListener('click', gameOver);
        }   

        const leftSideImages = theLeftSide.cloneNode(true);
        leftSideImages.removeChild(leftSideImages.lastChild);
        theRightSide.appendChild(leftSideImages); 
        
    function nextLevel(event) {
        event.stopPropagation();
        numberOfFaces  = 5;

        while (theLeftSide.firstChild) {
            theLeftSide.removeChild(theLeftSide.firstChild);
        }

        while (theRightSide.firstChild) {
            theRightSide.removeChild(theRightSide.firstChild);
        }
        
        generateFaces();
    }

    function gameOver() {
        alert('Game Over!');
        document.body.removeEventListener('click', gameOver);
        theLeftSide.lastChild.removeEventListener('click', nextLevel);
    }
    
    } 
</script>
</body>
</html>

CodePudding user response:

notice

for (let i = 0; i < numberOfFaces; i  ) {
    let face = document.createElement("img");
    ...
    theLeftSide.appendChild(face);

    // you do this in every loop
    theLeftSide.lastChild.addEventListener('click', nextLevel);
}   

put the theLeftSide.lastChild.addEventListener('click', nextLevel); outside loop for it to work

  • Related