Steps for creating a function to validate if two classes are identical

Currently, I am developing a memory game using JavaScript. One of the features I have implemented is toggling between two card faces by changing the class back and forth. Now, I am in the process of creating a function that will check if two game cards are matched. If they match, the images will remain flipped; otherwise, they will revert back to their original state.

// Declaration of variables for game elements
let gameTiles = document.getElementsByClassName('game_tile');
let cardFace = document.getElementsByClassName('card_face');
let cardMatchCheck = [];
let cardArray = 
[ "one", "one", "two", "two", "three", "three", 
 "four", "four", "five", "five", "six", "six", 
"seven", "seven", "eight", "eight", "nine", "nine", 
 "ten", "ten", "eleven", "eleven", "twelve", "twelve" ];

// Assigning class to div element through loop from the cardArray
// .className += enables adding to an already assigned class
// in this case "game_tile" (our button class)

for (let i = 0; i < gameTiles.length; i++) {
for (let j = 0; j < cardArray.length; j++) {
    gameTiles[i].setAttribute("class", cardArray[j]);
   } 
} 

// Click response (working)
let gameTileClick = document.getElementsByTagName('button');
for (let i = 0; i < gameTileClick.length; i++) {
    gameTileClick[i].addEventListener('click', changeCardImage);
}

  // Testing grounds:

// This function runs through all card classes and switches 
// between both card image states (back, front, back)
// Still need to work on implementing the pair recognition

function changeCardImage(cardArray) {
if (cardArray.className == 'one') {
    cardArray.className = 'card_one_img'
    cardMatchCheck.push(cardArray.className);
    cardMatch();
    cardMismatch();
} else if (cardArray.className == 'card_one_img') {
    cardArray.className = "one"    
}

... 

console.log(cardMatchCheck);


// Function for checking card match/mismatch 

function cardMatch() {
if (cardArray.className == cardArray.className) {
    console.log('match');
    }         
}   

function cardMismatch() {
if (cardArray.className != cardArray.className) {
    cardArray.className = 'card_face';
    }
}

If there's any formatting issue, please bear with me as this is my first SO post. Any guidance would be greatly appreciated. Thank you for taking the time!

Edit: To see what I have developed so far, here is the link: https://codepen.io/woolsox/pen/mMRPJK

Answer №1

Here are a couple of ideas to consider:

1) Your if else logic can be simplified to the following code snippet:

 var newArray= cardArray.className.split("_");
 cardArray.className = newArray.length>1?newArray[1]:"card_"+newArray[0]+"_img";

2) Another approach is to maintain a reference to the previous element:

var prevElement = null;
function handleCardClick(){
   if(prevElement){
    if(prevElement.className === this.className){
      alert("match found");
    }
     prevElement = null;
  }else{
     prevElement = this;
  }
 }

Answer №2

Just a friendly suggestion, not an answer.

One interesting feature is the classList property of elements which includes a toggle method. This means you can easily apply default styling to an element and then dynamically change its appearance by toggling classes on and off, similar to how you're switching between 'card_ten_img' and 'ten'. Another tip is to utilize event delegation by adding just one listener to the document, detecting clicks on cards and responding accordingly. Here's an example:

// Toggle inverted class if click target has class .card
function invertCard(evt) {
  var el = evt.target;
  if (el.classList.contains('card')) {
    el.classList.toggle('inverted');
   }
}

// Add listener to document to handle clicks on cards
document.body.addEventListener('click', invertCard, false);
/* Default style for a card */
.card {
  display: inline-block;
  float: left;
  width: 20px;
  height: 20px;
  border: 1px solid red;
  margin: 5px;
  text-align: center;
  color: black;
  background-color: white;
}

/* Additional style for inverted card */
.inverted {
  color: white;
  background-color: black;
}
<div class="card">A</div>
<div class="card">B</div>
<div class="card">C</div>

To enhance interaction further, consider creating a more versatile handleClick function that reacts based on the source of the click, its current state, game rules, and overall game state.

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

Storing numerous JSON records into an array by parsing them from a file

As a beginner in JS programming, I have a question that may seem trivial. Despite hours of searching online, I haven't been able to find a solution that works for me. I am dealing with multiple JSON feeds where each URL provides a multilayer JSON rec ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...

Which is more recommended to use in AJAX (XMLHttpRequest) - eventListener or readyStateChange method?

As I revisited a video from WWDC12 discussing advanced effects with HTML5, I couldn't help but notice that for the demo they utilized req.addEventListener("load",callback,true) instead of the usual onreadystatechange. This made me wonder: what differ ...

``The importance of properly formatting a text string before encoding it into

Currently in the process of converting an XML document to JSON via a PHP backend and then sending it back to the frontend using AJAX. This is achieved through the following code snippet: print_r(json_encode($result_xml)); If you want to view the response ...

Angular UI grid: Arranging numbers in a straight line at the decimal point

I am interested in aligning decimal numbers in Angular UI Grid as shown below. 11.293 .89 233424 .34345 I have considered different approaches such as using a cell template with aligned divs or transparent 0s. Has anyone successfully imp ...

What is the best way to generate a JSON output that contains the entire

The use of {foo|json} is effective for displaying only part of the $scope. Is there a way to pass the entire scope to the json filter? ...

"Enhance your webpage with a captivating opaque background image using Bootstrap

I'm new to exploring Bootstrap and I am currently experimenting with options for displaying content with a semi-transparent background image. Currently, I am using a "well" but I am open to other suggestions. I have managed to place the image inside t ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Utilize Object by referencing a string

I am trying to access an object from my node backend in React by using a string as a key. For example, if the string is 'Cat', I want to access the Cat object along with its corresponding key/value pairs. Here is an illustration of what the code ...

Modify an element on one webpage using a function called from another webpage

I am currently working on a website design that involves displaying images on various frames. While I have managed to change content across different frames, I am now exploring the possibility of changing content across different web pages. Here is the se ...

Query an array of objects for partial matches that are not case-sensitive, and then organize the results in alphabetical order

I am seeking assistance or guidance on which topics to explore for answers. As a newcomer to React, I have a code that successfully filters a list within the items object. However, I would like to switch to using a prepared JSON file instead. When I attem ...

"Transforming a query into a JSON array - a step-by-step

My query generates the following output: { key:1,label:"R. Bulan"} { key:2,label:"R. Bintang"} { key:3,label:"R. Akasia"} { key:4,label:"R. Guest Room"} This is my SQL query: select '{ '||'key:'||IDMEETINGROOM||''||',l ...

Angular 2 template can randomly display elements by shuffling the object of objects

I am working with a collection of objects that have the following structure: https://i.stack.imgur.com/ej63v.png To display all images in my template, I am using Object.keys Within the component: this.objectKeys = Object.keys; In the template: <ul ...

What is the best way to customize the appearance of Image tags located inside SVGs, whether they are in separate files or embedded within the code

I am developing a custom SVG editor application and facing an issue with implementing a highlighted effect when an <image> element is clicked. I have successfully accomplished this for other elements like <circle> by adjusting attributes such a ...

Dealing with multiple v-on:click events in Vue.js

Can I add multiple v-on:click events to the same element? I want to toggle a navigation menu and trigger a CSS animation on the element that toggles the navigation. <template> <div> <nav v-if="visible"> <ul&g ...

Superbase Email Forwarding

Is it possible to create a dynamic redirect link in the confirmation email that directs users to a specific page after creating an account? For instance: If a user visits the website using a link such as www.website.com/project/1 or /project/2 etc. and t ...

Creating objects that are a fraction of another's width

My goal is to create 3 responsive divs that fill the width of the window and adjust their width based on the window dimensions. However, I'm facing an issue with JavaScript where it seems to be miscalculating the window width, causing the objects to o ...

Encountered a problem with AngularUniversal prerendering: UnhandledPromiseRejectionWarning: Unable to locate NgModule metadata for 'class{}'

Objective The task may seem lengthy, but it's straightforward! Currently, I am utilizing Angular Universal for Server-Side Rendering (SSR) by following a tutorial. The Universal/express-engine has been installed, main.js is generated in the dist/pro ...

Observing data within an AngularJS service

I am currently working with a service called sharedData and a controller named HostController. My goal is to have the HostController monitor the saveDataObj variable within the sharedData service, and then update the value of host.dataOut, which will be re ...