Memory Game In Javascript With Source Code

Memory Game In Javascript With Source Code

The Memory Game In Javascript was developed using JavaScriptCSS and HTML, This Javascript Project With Source Code will put your short-term memory to the test. While playing this game, a sequence of images will emerge in a box-shaped region. To win the battle, the player must locate two identical images and click on them.

A Memory Game In Javascript Code is a straightforward HTML, CSS, and JavaScript project. In terms of the game’s mechanics, the user must click the same two photos in order to get points.

How to play Memory Game In Javascript?

  • Click on the cards or press the keyboard keys to reconstruct the pairs of images by turning them 2 by 2 and discover the image hidden underneath!
  • If the cards turned face up are the same (a pair), you win and get points for it!
  • Otherwise, the cards are automatically turned face down and you will lose your point!

This Javascript Project With Source Code also includes a downloadable javascript source code for free, just find the downloadable source code below and click to start downloading.

I have here a suggested list of Best JavaScript Projects with Source Code Free to download and I’m sure this can help you to improve your skills in JavaScript programming and web development as a whole.

To start executing a Memory Game In Javascript With Source Code,  makes sure that you have any platform in creating a JavaScriptCSS,  bootstrap, and HTML installed in your computer, in my case I will use Sublime Text.

Memory Game In Javascript With Source Code : Steps on how to create the project

Time needed: 5 minutes

These are the steps on how to create Memory Game In Javascript With Source Code

  • Step 1: Create a folder.

    First, create a folder and named it.
    memory game create folder

  • Step 2: Open the folder in “Sublime Text”.

    Second ,after creating a folder, open it in “sublime text“.
    memory game open folder

  • Step 3: Create a html file.

    Third, create a “html” file and save it as “index.html
    memory game html file

The code given below is for the html module

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="Description" content="Enter your description here"/>
<link rel="stylesheet" href="">
<link rel="stylesheet" href="" integrity="sha384-vSIIfh2YWi9wW0r9iZe7RJPrKwp6bG+s9QZMoITbCckVJqGCCRhc+ccxNcdpHuYu" crossorigin="anonymous">
<title>Memory Minder</title>

    <div class="text-center text-uppercase mt-5">
        <h1>Memory Game</h1>
        <p><strong>Test your Memory:</strong>Match the pairs as quickly as possible, in as few moves as possible</p>

    <div id="gameboard" class="container">
        <div class="row">
            <div class="col-3 gametile" id="tile1"></div>
            <div class="col-3 gametile" id="tile2"></div>
            <div class="col-3 gametile" id="tile3"></div>
            <div class="col-3 gametile" id="tile4"></div>
            <div class="col-3 gametile" id="tile5"></div>
            <div class="col-3 gametile" id="tile6"></div>
            <div class="col-3 gametile" id="tile7"></div>
            <div class="col-3 gametile" id="tile8"></div>
            <div class="col-3 gametile" id="tile9"></div>
            <div class="col-3 gametile" id="tile10"></div>
            <div class="col-3 gametile" id="tile11"></div>
            <div class="col-3 gametile" id="tile12"></div>
        <div class="row">
            <div class="col-4 label"><h3>Timer</h3></div>
            <div class="col-4 label"><h3>Moves</h3></div>
            <div class="col-4 label"><h3>Score</h3></div>
            <div class="col-4" id="timer"><div></div></div>
            <div class="col-4" id="clicks"><div></div></div>
            <div class="col-4" id="score"><div></div></div>
        <div class="row">
            <div class="col-6 mt-4">
                <button id="startGame" class="btn btn-success">Start Game</button>
            <div class="col-6 mt-4">
                <button id="endGame" class="btn btn-danger"> End Game </button>
            <div class="col-2 mx-auto">
                <button id="reset" class="btn btn-warning"><a style="text-decoration: none;" href="index.html">Reset</a></button>

In this module which is the html module of the simple project.

The code given below is for the css module

    @import url('');

    font-family: 'jokerman', cursive;
    background-color: skyblue;

    color: white;

    margin: 5vh auto;
    height: 60vh;
    width: 60vw;

    height: 15vh;
    width: 15vw;
    line-height: 15vh;
    background-color: #44445a;
    color: white;
    text-align: center;
    font-size: 0em;
    border: 2px solid #55555a

#timer div, #score div, #clicks div{
    margin: 10px auto 25px auto;
    height: 80px;
    line-height: 80px;
    text-align: center;
    border: 3px solid #555;
    background-color: #f5f5f5;
    border-radius: 10px;
    font-weight: 600;
    font-size: 2em;
    text-transform: capitalize;

    margin-top: 20px;
    text-transform: uppercase;
    color: white;
    text-align: center;

    text-align: center;
    width: 100%;
    padding: 2%;
    margin-bottom: 10%;
    font-weight: 600;
    font-size: 2.5em;

    font-size: 3em;

    font-size: 0em;
    background-color: #44445a;

    background-color: green;

    background-color: red;


In this module which is the css module of the simple project.

The code given below is for the javascript module

    //on page load -> generate game board;
window.onload = function(){
    console.log("Page Loaded")

//global variable

let i = 0;
let clicks;
let timeScore;

/*start button initiates game and starts counter
initiates game start on button press*/
let startButton = document.getElementById("startGame")
startButton.addEventListener("click", startGame);

function startGame() {
    tiles.forEach(tile => tile.addEventListener("click", displayTile));
    startButton.disabled = true;

//end button stops the game
document.getElementById('endGame').addEventListener("click", endGame);

function endGame() {
    function endTimer() {
        timeScore = document.getElementById("timer").innerText;
    randomOrderArray= [];
    startButton.innerText = "New Game";
    startButton.disabled = false;

/* createRandom number function
creates random number which will later be assigned an icon
creates an array of 12 random numbers*/
let randomOrderArray = [];
function setRandomTileOrder(numberOfTiles) {
    while (randomOrderArray.length < numberOfTiles) {
        let randomNum = Math.random();
        randomNum = randomNum * (numberOfTiles -1);
        randomNum = Math.round(randomNum) + 1;

        if (randomOrderArray.includes(randomNum)) {
        } else {

//Set tiles variable for use throughout code
const tiles = document.querySelectorAll(".gametile");

function setTiles(){
    for(tile of tiles){
        tile.innerHTML = randomOrderArray[i];
    //replace numerical values with icon pairs

    if (tile.innerText < 3) {
        tile.innerHTML = rocket;
        tile.setAttribute("icon", "rocket")
    } else if (tile.innerHTML < 5) {
        tile.innerHTML = bacteria;
        tile.setAttribute("icon", "bacteria")
    } else if (tile.innerHTML < 7) {
        tile.innerHTML = cocktail;
        tile.setAttribute("icon", "cocktail")
    } else if (tile.innerHTML < 9) {
        tile.innerHTML = football;
        tile.setAttribute("icon", "football")
    } else if (tile.innerHTML < 11) {
        tile.innerHTML = pizza;
        tile.setAttribute("icon", "pizza")
    } else if (tile.innerHTML < 13) {
        tile.innerHTML = kiwi;
        tile.setAttribute("icon", "kiwi")
    } else {
        console.log("Error: too many tiles");

//Timer Function -> starts timer when game is started end when game is complete or game is cancelled.
let count;

function startTimer() {
    clearInterval(timer); //clears timer before timer starts. This fixes issue if timer is triggered again, when already running. 
    count = 0, timer = setInterval(function () {
        count = count++;
        document.getElementById("timer").firstChild.innerText = count++;

        //end timer when timer reaches -1, This displays 0.
        if (count === 60) {
            document.getElementById("timer").firstChild.innerText = "Game Over";
    }, 1000);

/* icon assign function -> replaces random numbers with icon pairs
when icon assigned, tile is also assigned an attribute icon variables */
let football = `<i class="fas fa-football-ball"></i>`;
let mask = `<i class="fas fa-ufo"></i>`;
let pizza = `<i class="fas fa-pizza-slice"></i>`;
let lightning = `<i class="far fa-bolt"></i>`;
let bulb = `<i class="fal fa-lightbulb"></i>`;
let rocket = `<i class="fas fa-rocket"></i>`;
let bacteria = `<i class="fas fa-bacterium"></i>`;
let kiwi = `<i class="fas fa-kiwi-bird"></i>`;
let cocktail = `<i class="fas fa-cocktail"></i>`;

const selectedTile = ''
let tileIcon;
let tileIcons =[];
let tileIds =[];

//displayTile -> function which listens for click event and displays tile value on click
tiles.forEach(tile => tile.addEventListener("click", displayTile));
let n = 0;

function displayTile(e) {
    //reveal tile by changing bg color and changing font-size from 0 to 3em;
    // logs the value of the tile's icon and Id
    tileIcon ="icon");
    let tileId ="id");
    // this counts number of clicks

    if(tileIcons.length % 2 == 0){
    checkMatch(tileIcons, tileIds,n)
    n = n+2;

function checkMatch(tileIcons, tileIds,n){
        if(tileIcons[n] !== tileIcons[n+1]){
            console.log("no match");
            }, 1000);  
        } else {
            document.getElementById(tileIds[n]).style.backgroundColor = "green";
            document.getElementById(tileIds[n+1]).style.backgroundColor = "green";
            document.getElementById(tileIds[n]).removeEventListener("click", displayTile);
            document.getElementById(tileIds[n+1]).removeEventListener("click", displayTile); 

//countClicks -> calculates number of user clicks -> needed to calculate score
function countMoves(){
    clicks = n;
    document.getElementById("clicks").firstChild.innerHTML = clicks;

//ClearTiles -> Clear tiles when new game is started;
function clearTiles(){
    for(let n = 0; n < tiles.length; n++){
        tiles[n].style.fontSize = "0em";
        tiles[n].style.backgroundColor = "#44445a";

/*match tiles -> when one tile is clicked and displayed, check if next tile clicked has the same attribute value
if match icons remain displayed and correctly guessed tiles become disabled. */

//countCorrectAnswers -> count the number of tiles with value correct. each time a pair of tiles are matched, add 1 to the coundCorrectAnswers value;

//completeGAme -> When the number of correct answers == the number of cells the game can end.

//calculateScore -> adds number of clicks and elapsed time to calculate score & displays score upon game completion. 
function calculateScore(){
    timeScore = parseInt(timeScore);
    let calculatedScore = (timeScore + clicks);
    document.querySelector("#score").firstChild.innerHTML = calculatedScore;
//refresh/reset -> click button, invokes endGame() the reset tiles values, and return their default styling.

//additional levels of difficulty

//1. generateRandomColor -> generates a random background color, to make matching harder as game progresses
let newRGB;

function generateRGBVal() {

    function generateRandomColor() {
        let r = Math.random();
        r = r * 255;
        r = Math.round(r);
        return r;

    let rgbValue = [];
    for (let i = 0; i <= 2; i++) {
        let singleVal = generateRandomColor();
    newRGB = `rgb(${rgbValue[0]},${rgbValue[1]},${rgbValue[2]})`;
    return newRGB;
//2. addAdditional tiles -> 12, 16, 20, 24
//3. Reduce time -> decrease amount of time available to complete the game. 
//4. change icons to a math problem to be matched to the correct answer;

//additional iterations/Future development
// publish leaderboard;
//use api to generate random icon or picture

function resetTiles(){
    for(tile of tiles){ ="#44445a";


In this module which is the javascript module of the simple project.

Project Output

Memory Game In Javascript Output
Memory Game In Javascript Output
Project Name :Memory Game In Javascript
Project Platform :JavaScript
Programming Language Used:php,javascript,html,css
Developer Name
IDE Tool (Recommended):Sublime
Project Type :Web Application
Upload Date:July 19, 2021

Downloadable Source Code


This JavaScript Project With Source Code is simply in HTMLCSS, and JavaScript. To start creating this Simple Javascript Project With Source Code, make sure that you have basic knowledge in HTMLCSS and Javascript.

This Javascript Game Project also includes a downloadable Javascript Game Project With Source Code for free.

Related Articles


If you have any questions or suggestions about Memory Game In Javascript With Source Code , please feel free to leave a comment below.

Leave a Comment