Search code examples
javascriptevent-handlingmouseeventgame-development

Is it possible to add an image through event.target?


I want to make a simple game in a 7x7 grid, where I want to place on click images from an array, and then check for matches (like in connect four)

I have a grid, with all its squares in HTML divs, like this :

<div class="grid">
      <div class="square" id="1"></div>
      <div class="square" id="2"></div>
      <...............................>
      <div class="square" id="49"></div>

and some images stored in an array in app.js :

document.addEventListener("DOMContentLoaded", () => {
    const squares = document.querySelectorAll(".square")
    const scoreDisplay = document.getElementById("result")
    let score = 0;
    squares[24].style.backgroundImage = "url('res/middle.png')"
    const cards = [
        {
            name: 'blue',
            img: 'res/blue.png'
        }, 
         {
            name: 'yellow',
            img: 'res/yellow.png'
        }, 
        {
            name: 'red',
            img: 'res/red.png'
        }, 
        {
            name: 'orange',
            img: 'res/orange.png'
        }, 
        {
            name: 'green',
            img: 'res/green.png'
        }, 
        {
            name: 'pink',
            img: 'res/pink.png'
        }, 
        {
            name: 'ivory',
            img: 'res/ivory.png'
        }, 
    ]

The random image of the array does not appear on the grid, however the score updates and there are no console errors.

let randomCard = Math.floor(Math.random() * cards.length)
   

//    clickedPosition = ?

   squares.forEach(square => {
        square.addEventListener('click', function(e) {
            if(square.id !== squares[24] ) {
                score ++;
                scoreDisplay.textContent = score
                e.target.style.backgroundImage = randomCard.img
                

            } else {

            }
        })
   })

})

Solution

  • I figured it out!

    Changed the cards array to look like this :

    const cards = [ "url('res/blue.png')", "url('res/yellow.png')", "url('res/red.png')", "url('res/orange.png')", "url('res/green.png')", "url('res/pink.png')", "url('res/ivory.png')" ]

    and now a single image will appear on click (unfortunately not a random one, but this is progress! )

     e.target.style.backgroundImage = cards[randomCard]