Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Create a Simon Game using HTML CSS & JavaScript
Next article icon

Build a Memory Card Game Using HTML CSS and JavaScript

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of both cards are matching or not. If the faces of both cards are the same, then the player can keep those cards face up and continue. Otherwise, the player needs to put the picked cards back face down and continue by selecting other cards. In this article, we are going to build a memory game with the help of HTML, CSS, and JavaScript.

Preview:

cardFlipPreview

Technologies Used:

  • HTML
  • CSS
  • JavaScript

Approach:

  • Create a basic structure for you games using the HTML tags like div, heading, paragraph, img etc. with the particular Classes and Ids associated with each one of them.
  • Now, select the elements with the help of class and id CSS selectors to style the elements and make the UI attractive and interactive.
  • After HTML and CSS, its time to get all the required elements inside the JavaScript code and apply logic on them.
  • In JavaScript, we will create an array of objects with the image link, respective alt value and ID for each item of the array.
  • In the next part, a callback function will be created to handle the click event of the cards. This function will handle the card flips whether the flipped card is same or different by removing and ading the classes to the elements.
  • Next, another callback function will be created to handle the Restart Game button click, it will shuffle all the cards and flip them backward again to restart the game.
  • At the end, we will check for the condition where game ends and show the result to the user by using the window.alert() method of JavaScript.

Example: The below example will explain how you can create an memory card game using HTML, CSS and JavaScript:

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <link rel="stylesheet" href="style.css">     <title>Memory Card Game</title> </head>  <body>     <div class="container">         <div id="dynamic-cards" class="game-container">             <div class="heading-container">                 <h1 class="gfg-heading">                       GeeksforGeeks                   </h1>                 <h2 class="game-heading">Click any card to flip it!</h2>             </div>             <div class="cards-container">                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="1"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102835/html5Image.png"                         alt="HTML Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="2"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102834/JSImage.jpg"                         alt="JavaScript Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="3"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102834/CSS3Image.png"                         alt="CSS Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="4"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102834/JSImage.jpg"                         alt="JavaScript Image" class="card-image">                 </div>                  <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="5"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102835/html5Image.png"                         alt="HTML Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="6"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/vueImage.png"                         alt="VUE Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="7"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102834/CSS3Image.png"                         alt="CSS Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="8"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/reactImage.png"                         alt="React Image" class="card-image">                 </div>                  <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="9"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/vueImage.png"                         alt="VUE Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="10"                         src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/AngularImage.png"                         alt="Angular Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="11"                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/reactImage.png"                         alt="React Image" class="card-image">                 </div>                 <div class="card">                     <img                          src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122105630/gfgImage.png"                         class="outline-image">                     <img id="12"                         src= "https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/AngularImage.png"                         alt="Angular Image" class="card-image">                 </div>             </div>              <div class="progress-container">                 <div class="move-counter">Moves: 0</div>                 <button id="restart" class="restart-button">                       Restart Game                   </button>             </div>         </div>     </div>      <script src="script.js"></script> </body>  </html> 
CSS
body{     margin: 0;     padding: 0;     box-sizing: border-box; }  .container{     display: flex;     align-items: center;     justify-content: center;     height: 100vh; }  .game-container{     width: 800px;     padding: 20px;     border-radius: 10px;     row-gap: 15px;     box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;     background-image: linear-gradient(90deg, #fffbd5, #ccc); }  .cards-container{     display: grid;     grid-template-rows: 125px 125px 125px;     grid-template-columns: 200px 200px 200px 200px;     grid-gap: 20px 10px;     place-items: center; }  .heading-container{     text-align: center; }  .gfg-heading{     color: #0E9D57; }  .card{     justify-items: center;     display: flex;     align-items: center;     position: relative;     cursor: pointer; }  .outline-image{     position: absolute;     border-radius: 10px;     top: 0;     left: 0;     height: 125px;     width: 125px;     border-radius: 50%; }  .card-image{     height: 125px;     width: 125px;     transform: rotateY(90deg);      transition: all ease-in 0.25s;     mix-blend-mode: multiply; }  .progress-container{     text-align: center;     display: flex;     justify-content: space-around;     width: 100%;     margin: 50px 0 20px 0; }  .move-counter{     padding: 10px 20px;     border-radius: 25px;     border: 1px solid #ccc; }  .restart-button{     padding: 10px 20px;     background-color: #0E9D57;     border: none;     border-radius: 25px;     color: #fff;     cursor: pointer; }  .restart-button:hover{     background-color: transparent;     border: 1px solid #0E9D57;     color: #0E9D57; }  /* Dynamic classes that are being added by JavaScript */ .toggled .card-image {      transform: rotateY(0deg);      transition-delay: 0.25s;  }   .item .outline-image {      transition: all ease-in 0.25s;      transition-delay: 0.25s;  }     .toggled .outline-image {      transform: rotateY(90deg);      transition-delay: 0s;  }  @media screen and (max-width: 767px) {     .game-container{         width: 100%;     }          .cards-container{         grid-template-rows: 125px 125px 125px 125px;         grid-template-columns: 33% 33% 33%;         grid-gap: 10px 10px;     }      .outline-image{         height: 100px;         width: 100px;     }          .card-image{         height: 100px;         width: 100px;     }      .progress-container{         margin: 10px 0 10px 0;     }      } 
JavaScript
const cards =      document.getElementsByClassName('card'); let allImages = document.getElementsByClassName('card-image'); let movesDisplay = document.querySelector('.move-counter'); let toggledCardsArray = []; let move = 0; let winCount = 0; const restart = document.getElementById('restart');  const imagesLinkArray = [     {         id: 1,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/AngularImage.png',         newAlt: 'Angular Image'     },     {         id: 2,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102835/html5Image.png',         newAlt: 'HTML Image'     },     {         id: 3,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102834/JSImage.jpg',         newAlt: 'JavaScript Image'     },     {         id: 4,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/reactImage.png',         newAlt: 'React Image'     },     {         id: 5,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/vueImage.png',         newAlt: 'Vue Image'     },     {         id: 6,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102834/JSImage.jpg',         newAlt: 'JavaScript Image'     },     {         id: 7,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/vueImage.png',         newAlt: 'Vue Image'     },     {         id: 8,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102835/html5Image.png',         newAlt: 'HTML Image'     },     {         id: 9,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102834/CSS3Image.png',         newAlt: 'CSS Image'     },     {         id: 10,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/AngularImage.png',         newAlt: 'Angular Image'     },     {         id: 11,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102834/CSS3Image.png',         newAlt: 'CSS Image'     },     {         id: 12,         image:  'https://media.geeksforgeeks.org/wp-content/uploads/20231122102833/reactImage.png',         newAlt: 'React Image'     } ]  // function to restart the game const restartGame = () => {     let toggledCard =          document.getElementsByClassName('card toggled');     imagesLinkArray.sort(() => Math.random() - 0.5);     Object.values(toggledCard).forEach(function (el) {         setTimeout(() => {             el.classList.remove("toggled");         }, 0);     })     toggledCardsArray.length = 0;     move = 0;     winCount=0;     movesDisplay.innerText = `Moves: ${move}`;     let allImagesSrc = document.getElementsByClassName('card-image');     Object.values(allImagesSrc).forEach((el, index)=>{         el.src = imagesLinkArray[index].image;         el.alt = imagesLinkArray[index].newAlt;         el.id = imagesLinkArray[index].id     })  } restart.addEventListener('click', restartGame);  //checking for the last clicked and current  //clicked cards and applying changes accordingly for (var i = 0; i < cards.length; i++) {     cards[i].addEventListener('click', function () {         this.classList.add("toggled");         toggledCardsArray.push(this);         let thisImgSrc = this.querySelector('.card-image').src;         let previousImgSrc =          toggledCardsArray[toggledCardsArray.length - 2].querySelector('.card-image').src;         if(thisImgSrc !== previousImgSrc) {             toggledCardsArray.forEach(function (el) {                 setTimeout(() => {                     el.classList.remove("toggled");                 }, 500);             })             toggledCardsArray.length = 0;             move++;         }         else{             toggledCardsArray.length = 0;             move++;             winCount++;         }         movesDisplay.innerText = `Moves: ${move}`;         if(winCount===6){             setTimeout(()=>{                 alert(`Congratulations!!! You won the game in ${move} moves.`)             }, 300)         }     }) } 

Output: The below output will show you a demo of the above card game:


Next Article
Create a Simon Game using HTML CSS & JavaScript

M

mansigeekso9ii
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Projects

Similar Reads

    Create a snake game using HTML, CSS and JavaScript
    Snake Game is a single-player game where the snake gets bigger by eating the food and tries to save itself from the boundary of the rectangle and if the snake eats their own body the game will be over.Game Rules:If the snake goes out of the boundary or eats its own body the game will be over.Prerequ
    4 min read
    Design Dragon's World Game using HTML CSS and JavaScript
    Project Introduction: "Dragon's World" is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon.  The project will contain HTML, CSS and JavaScript files. The H
    6 min read
    Word Guessing Game using HTML CSS and JavaScript
    In this article, we will see how can we implement a word-guessing game with the help of HTML, CSS, and JavaScript. Here, we have provided a hint key & corresponding total number of gaps/spaces depending upon the length of the word and accept only a single letter as an input for each time. If it
    4 min read
    Build a Memory Card Game Using HTML CSS and JavaScript
    A memory game is a type of game that can be used to test or check the memory of a human being. It is a very famous game. In this game, the player has some cards in front of him and all of them facing down initially. The player has to choose a pair of cards at one time and check whether the faces of
    6 min read
    Create a Simon Game using HTML CSS & JavaScript
    In this article, we will see how to create a Simon Game using HTML, CSS, and JavaScript. In a Simon game, if the player succeeds, the series becomes progressively longer and more complex. Once the user is unable to repeat the designated order of the series at any point, the game is over.Prerequisite
    5 min read
    Create a Minesweeper Game using HTML CSS & JavaScript
    Minesweeper is a classic puzzle game that challenges your logical thinking and deduction skills. It's a great project for developers looking to improve their front-end web development skills. In this article, we'll walk through the steps to create a Minesweeper game using HTML, CSS, and JavaScript.
    4 min read
    Whack-a-Mole Game using HTML CSS and JavaScript
    Whack-A-Mole is a classic arcade-style game that combines speed and precision. The game is set in a grid of holes, and the objective is to "whack" or hit the moles that randomly pop up from these holes. In this article, we are going to create Whack-a-Mole using HTML, CSS and JavaScript.Preview Image
    3 min read
    Simple HTML CSS and JavaScript Game
    Tap-the-Geek is a simple game, in which the player has to tap the moving GeeksForGeeks logo as many times as possible to increase their score. It has three levels easy, medium, and hard. The speed of the circle will be increased from level easy to hard. I bet, it is very difficult for the players to
    4 min read
    Design Hit the Mouse Game using HTML, CSS and Vanilla Javascript
    In this article, we are going to create a game in which a mouse comes out from the holes, and we hit the mouse with a hammer to gain points. It is designed using HTML, CSS & Vanilla JavaScript.HTML Code:First, we create an HTML file (index.html).Now, after creating the HTML file, we are going to
    5 min read
    Create a 2D Brick Breaker Game using HTML CSS and JavaScript
    In this article, we will see how to create a 2D Brick Breaker Game using HTML CSS & JavaScript. Most of you already played this game on your Mobile Phones where you control a paddle to bounce a ball, aiming to demolish a wall of bricks arranged at the top of the screen. 2D Brick Breaker Game is
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences