Choosing individual div elements to assign attributes using event listeners

I've developed a Tic-Tac-Toe game but now I'm trying to figure out how to add colors to the winning squares or draw a line. The CSS for creating the square or line is simple, but I'm unsure about selecting only the winning squares when my winning combinations are structured like this:

const winningCombos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]

Players' moves are stored in an array to check the combinations later. For instance, if one player takes 5 moves to win, we might need only 3 winning squares.

xChoices = [0,1,3,6] // where 0,3,6 are winners and I want to highlight them with color or draw a line

This is how I validate the combinations:

function checkForXWinner(){
        return winningCombos.some(combo =>{
            return combo.every(e =>{
                return xChoices.includes(e)
            })
        })
    }

    function checkForOWinner(){
        return winningCombos.some(combo =>{
            return combo.every(e =>{
                return oChoices.includes(e)
            })
        })
    }

You can find the code on jsfiddle by clicking the link below. Cheers!

https://jsfiddle.net/6zbdgrmy/

Answer №1

To actually color those squares, you can easily locate the corresponding array within the multidimensional array and then proceed to color each square individually

For instance:

const winningPatterns = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
]

selectedSquares = [0, 1, 3, 6]

const winPatternIndex = winningPatterns
  .map(arr => arr.every(sqr => selectedSquares.includes(sqr)))
  .findIndex(x => x)

for (let i = 0; i < winningPatterns[winPatternIndex].length; i++) {
  console.log('color:', winningPatterns[winPatternIndex][i])
}

Answer №2

Give it a go!

 elements = Array.from(document.querySelectorAll('.col'))
 const winningSequence = () => {
   let victoriousSequence = []
   winningCombinations.forEach(sequence => {
     if (elements[sequence[0]].innerHTML == elements[sequence[1]].innerHTML && elements[sequence[0]].innerHTML == elements[sequence[2]].innerHTML && elements[sequence[0]].innerHTML != "")
       victoriousSequence = sequence
   })
   return victoriousSequence
 }

This function identifies the triumphant sequence. You are now able to manipulate the divs at the victoriousSequence position and add your desired CSS styles to them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting the CSS URL to work when using a leading slash?

I am attempting to utilize a background-image with a "root-relative" path like this: background-image: url("/img/bg.jpg");. In Chrome, the property is showing correctly but the image does not appear. When I change it to http://localhost:8080/img/bg.jpg, t ...

Maintaining fixed position for cursor events in CSS

Here is a simple popup I created using tailwindcss to display project descriptions. Take a look at the code snippet below: // Code snippet here... I am facing an issue where both the container (outer div) and the first inner div have the same click event. ...

Switch the header from left to right movement for mobile devices

I am dealing with two headers in my layout <section> <header class="col-lg-9"> <!-- some content --> </header> <header class="col-lg-3"> <!-- some content --> </header> </section ...

Capable of generating accounts using Postman, experiencing difficulties with creating accounts from React

Currently, I am working on a project that utilizes a React/Spring Boot/MYSQL stack and I have encountered an error message stating "POST 415: SyntaxError: Unexpected end of input at line 67". Line 67 is as follows: }).then(res => res.json()) This sect ...

The functionality of ZoneAwarePromise has been modified within the Meteor framework

After updating to the latest Angular 2.0.1 release on Meteor 1.4.1.1, I'm facing an error that says: Zone.js has detected that ZoneAwarePromise (window|global).Promise has been overwritten I've attempted running meteor update and meteor reset, b ...

What could be the reason for the ineffective custom error handling in mongoose?

In an attempt to improve the readability of error messages before they are displayed on the frontend, I am working on handling the required validation error as shown below: UserSchema .post('save', function (error, doc, next) { console.log ...

Tips for showcasing live data in Material-UI's table component

My challenge lies in displaying tabular data fetched from an API in a Material-UI Table. Specifically, I aim to exhibit the fields id and name stored within groups. How can I achieve this result? Beneath is my current code snippet which runs without error ...

CSS - Issue with table cell height exceeding in Mozilla Firefox and Internet Explorer

Examining the code below <div style="border:solid 5px orange;width:400px;height:400px"> <div style="display:table;border:solid 1px red;width:100%;height:100%"> <div style="display:table-row;border:solid 1px blue"> <div sty ...

Revamping CSS for a Responsive Wordpress Tesseract Theme

I'm currently in the process of developing a website using the Tesseract theme at thevandreasproject.com. However, I have encountered an issue with responsiveness when integrating the SiteOrigins PageBuilder plugin. The compatibility between PageBuild ...

Sending a request to multiple APIs using a GET method

Issue: I am facing a challenge with handling 47 URLs, each varying by their last one or two characters from 1 to 47. For instance: https://example.com/api/data?number=1 <--- the number at the end ranges from 1 to 47 My objective is to retrieve data ...

Displaying PDF content in a new browser tab by utilizing JavaScript

Currently, I am utilizing the struts2 framework alongside dojo for the UI. My goal is to display a PDF in a new browser window. The PDF inputstream is obtained from the server through a standard AJAX call using the GET method (not utilizing a Dojo AJAX cal ...

Sending the complete data from an HTML table to a web method

Is there a way to pass the data from a dynamically generated HTML table grid to a web method using jQuery AJAX? The table grid creates multiple rows on button click at runtime, and I need to send the entire table data. Please refer to the following snaps ...

Displaying Database Content on Screen Instead of index.html in Node/Express

I'm currently working with Node.js, however, when I try to access my localhost all I see is the database data in JSON format instead of my index.html page. This issue doesn't happen when using localhost, so I'm not sure why it's not dis ...

How can we optimize axios requests with lodash debounce?

Utilizing a state prop named network busy status to control elements in the UI. Due to the rapid changes in status, my spinner appears overly active. Is there a simple method, utilizing lodash _.debounce, to throttle this section of code? const instance ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

What could be causing the JSON output to appear in a disordered fashion?

I am attempting to retrieve weather information for 8 different locations. Utilizing a weather API that requires longitude and latitude, it returns JSON output with the weather data for each location. I provided the coordinates in sequential order from 0 t ...

What is the best way to convert a deeply nested PHP array/object into JSON format?

For those who want a shorter explanation, here it is: I have a JavaScript array filled with objects. Some properties of these objects contain arrays of objects, which in turn may have more arrays or objects nested within them. This results in 5 levels of n ...

Unique CSS styling technique

Is there a way to design a unique form similar to the one shown below using CSS? ...

Setting size using percentages in Semantic-UILet's explore how to define the size

Since discovering semantic-ui a few days ago, I've been impressed and have decided to switch my app from Bootstrap 3 to semantic-ui. I could use some assistance here. I'm attempting to split the body of the page into two parts. I would like the ...

The translation of popups using ngx-translate in Javascript is not functioning properly

When I click on my request, the content "Are you sure?" is not changing to the required language. This issue is located in list.component.html <button type="button" (click)="myrequest(item.Id)">Request View</button> The fu ...