skip to Main Content

I was making a box guessing game where there was multiple divs and one of them was the correct one.

The user should click a box to see if it was the correct box or not.

The HTML:-

  <body>
    <div class = "wrapper">
      <div id="box1" class="box"></div>
      <div id="box2" class="box"></div>
      <div id="box3" class="box"></div>
      <div id="box4" class="box"></div>
      <div id="box5" class="box"></div>
      <div id="box6" class="box"></div>
    </div>
  </body>

I gave all the boxes the (box) class and gave each box its own ID

then I made a variable that stores a random number (randomNum) which is from 0-5 and made a variable for each box and made an array called boxes so tha the correct box is boxes[randomNum]

const box1 = document.getElementById("box1");
const box2 = document.getElementById("box2");
const box3 = document.getElementById("box3");
const box4 = document.getElementById("box4");
const box5 = document.getElementById("box5");
const box6 = document.getElementById("box6");

let boxes = [box1, box2, box3, box4, box5, box6];

let randomNum = Math.floor(Math.random() * 6);

now I need to check if the box that is clicked is the correct box or not

I tried making a function that checks if the box that is clicked is equal to the boxes[randomNum] but I had trouble with referencing the clicked box

Does anyone know how I can get the clicked box?

4

Answers


  1. To do what you require you can determine the index of the clicked .box within its parent using parentNode.children, and comparing this to the random number you generated:

    const elementIndexInParent = el => [...el.parentNode.children].indexOf(el);
    const boxes = document.querySelectorAll('.wrapper .box');
    const randomNum = Math.floor(Math.random() * boxes.length + 1);
    
    boxes.forEach(box => {
      box.addEventListener('click', e => {
        const index = elementIndexInParent(e.target) + 1;
        console.log(`${index} is the ${index === randomNum ? 'right answer!' : 'wrong answer.'}`);
      });
    });
    .box {
      display: inline-block;
      padding: 20px;
      border: 1px solid #C00;
      background-color: #CCC;
    }
    <div class="wrapper">
      <div id="box1" class="box">1</div>
      <div id="box2" class="box">2</div>
      <div id="box3" class="box">3</div>
      <div id="box4" class="box">4</div>
      <div id="box5" class="box">5</div>
      <div id="box6" class="box">6</div>
    </div>
    Login or Signup to reply.
  2. When you subscribe to the click event, the event object is passed as the first parameter. event object has property target that contains the element that has been clicked. You can use method indexOf of an Array to find your div, as they are equal by reference:

    const box1 = document.getElementById("box1");
    const box2 = document.getElementById("box2");
    const box3 = document.getElementById("box3");
    const box4 = document.getElementById("box4");
    const box5 = document.getElementById("box5");
    const box6 = document.getElementById("box6");
    
    let boxes = [box1, box2, box3, box4, box5, box6];
    
    let randomNum = Math.floor(Math.random() * 6);
    
    function onClick(event) {
      if (isCorrectDiv(element.target)) {
        //do stuff
      }
    }
    
    function isCorrectDiv(element) {
      return boxes.indexOf(element) === randomNum;
    }
    
    Login or Signup to reply.
  3. Use querySelectorAll instead of getting each element by its id and then use addEventListener generate your randomNumber and concatenate the "box" string to the number then compare with the selected box id to be able to tell which box was clicked.

    Edit: moved the random number generator inside the eventListener so that it generates a new number, everytime you pick a new box

    const boxes = document.querySelectorAll(".box");
    
    boxes.forEach(x => {
      x.addEventListener("click", function(e) {
        let randomNum = Math.floor(Math.random() * 6) + 1;//we add +1 because this will generate a random number from 0 to 5
        let chosenBox = "box" + randomNum;
        if (e.target.id == chosenBox) {
          console.log(e.target.id + " is the right box")
        } else {
          console.log(e.target.id + " is not the right box, the right choice was " + chosenBox);
        }
      })
    })
    <div class="wrapper">
      <div id="box1" class="box">box1</div>
      <div id="box2" class="box">box2</div>
      <div id="box3" class="box">box3</div>
      <div id="box4" class="box">box4</div>
      <div id="box5" class="box">box5</div>
      <div id="box6" class="box">box6</div>
    </div>
    Login or Signup to reply.
  4. You do not need ID attributes. You just need to generate a random integer from 1 to 6, and determine if the box is correct based on the click target.

    const randInt = (min, max) => {
      if (max === undefined) { max = min; min = 0; }
      return Math.floor(Math.random() * (max - min + 1)) + min;
    };
    
    const
      boxes = document.querySelectorAll('.wrapper .box'),
      randomNum = randInt(1, boxes.length);
    
    const handleClick = (e) => {
      const
        boxValue = +e.target.textContent.trim(),
        isCorrect = boxValue === randomNum;
      e.target.classList.add(isCorrect ? 'correct' : 'wrong');
      console.log(`${boxValue} is ${isCorrect ? 'correct!' : 'the wrong answer.'}`);
    };
    
    const removeHighlight = (e) => {
      e.target.classList.remove('correct', 'wrong');
    };
    
    // Add event listeners
    boxes.forEach(box => box.addEventListener('click', handleClick));
    boxes.forEach(box => box.addEventListener('mouseleave', removeHighlight));
    .as-console-wrapper { max-height: 5rem !important; }
    
    *, *::before, *::after { box-sizing: border-box; }
    
    html, body {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    body {
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding: 0.5rem;
    }
    
    .wrapper {
      display: grid;
      grid-template-columns: repeat(3, auto);
      gap: 0.5rem;
    }
    
    .box {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 2rem;
      height: 2rem;
      border: thin solid grey;
    }
    
    .box:hover {
      cursor: pointer;
      background: yellow;
    }
    
    .box.correct:hover {
      background: lime;
    }
    
    .box.wrong:hover {
      background: red;
    }
    <div class="wrapper">
      <div class="box">1</div>
      <div class="box">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
      <div class="box">6</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search