JavaScript Fun! Build a Memory Game | Chris Dixon | Skillshare

Playback Speed

  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

JavaScript Fun! Build a Memory Game

teacher avatar Chris Dixon, Web Developer & Online Teacher

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

    • 1.

      Welcome To The Class!


    • 2.

      What You Will Need For This Class


    • 3.

      Share Your Work On Skillshare!


    • 4.

      Project Setup & HTML


    • 5.

      CSS Styling


    • 6.

      Selecting Random Colors


    • 7.

      Creating The Grid Of Squares


    • 8.

      Listening For Clicks


    • 9.

      Checking For a Match


    • 10.

      Handling a Match


    • 11.

      Tracking The Score & End Of Game


    • 12.



    • 13.

      Follow Me On Skillshare!


  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

Welcome to the Javascript fun series! 

You can find all of the code and project stages here:

For web design or development, there are 3 must-know technologies, HTML, CSS, and Javascript.

The main aim of the JavaScript fun series is to take your knowledge of these 3 (only a little is required!), and put them into practice by building a series of educational, yet fun projects that show you exactly how they work perfectly together. Working on projects and solving problems is a great way to learn.

The project we will build in this class will be a Javascript Memory Game. We show the player a grid of squares, then when clicked on, the background color is revealed. The idea is to find matching pairs to complete the game. Wrong guesses then once again hide the background color so the player needs to remember each one.

All the required tools are free to download, I will be using the following:

Visual Studio Code Text Editor:​

Chrome Web Browser:

We begin by creating the user interface with HTML. We then apply styling using CSS. 

Then we add Javascript, this is where the real magic happens! 

You will learn things such as:

  • Creating HTML interfaces
  • Styling with CSS
  • Incorporating JavaScript and linking external files
  • Variables / Constants
  • Functions
  • Event handlers
  • Manipulating the DOM
  • Loops
  • Arrays & Array Methods / Properties
  • Animations
  • Conditionals
  • Javascript Math & Random numbers
  • And much more!

So if you are looking to move on and put your skills into practice by building real projects, I hope to see you in class!

Meet Your Teacher

Teacher Profile Image

Chris Dixon

Web Developer & Online Teacher

Top Teacher

Hello, My name is Chris and I am a Web Developer from the UK. I am an experienced trainer leading web development bootcamps and also teaching online courses.

My main areas of interest are Vue.js, WordPress, Shopify, Javascript, eCommerce, and business. I am passionate about what I do and about teaching others. 

Whatever your reason for learning to build websites you have made an excellent career choice.

My personal motivation was to become my own boss and have more freedom and flexibility in my life. I also enjoy the technical challenge it provides and the way it constantly evolves. I built my first website back in 1999 and I have watched the web evolve into what it is today.

I try to make my courses enjoyable and try to remember what it was like wh... See full profile

Level: Beginner

Class Ratings

Expectations Met?
  • 0%
  • Yes
  • 0%
  • Somewhat
  • 0%
  • Not really
  • 0%

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. Welcome To The Class!: Hi, welcome to this class. If you are a web development beginner and just wanted to jump in and build some fun projects. Then this is the class for you. Idea behind this series is to show you what we can do when combined in HTML, CSS and JavaScript. Not going to be using any templates and in libraries, any boilerplates or any frameworks. Instead, we're going to build our projects completely from scratch using these three technologies. Project for this class is a memory game. And the idea is we have a grid of squares. The play link clicks on a pair of squares to reveal the colors and tries to find a match. If they get an incorrect match, the squares once again hidden. The player must try to remember what each full awards for the next attempt. The colors also random, so they're in a different location for each game. This game will be built completely from scratch. We'll begin by building the HTML structure. Before I didn't have styling and also the layout with CSS, along with lighter adding animations when there is a match and also when there is no much. Most of our time will be spent writing JavaScript, including generating the squares with random colors, dealing with matches and no matches, packing the score underlain the end of the game. And so much more. We'll cover many of the JavaScript fundamentals which you need to know, such as variables, functions, working with the DOM, events, conditionals, and many more. So thanks for checking out this class and I'll see you in the first lesson. 2. What You Will Need For This Class: Well, I'll go into waste anytime in jumping in and built in our project. Just before we do though, there is a couple of things which we need to get going. First of all, we need a web browser and you can use any web browser which you prefer, and what you're using Google Chrome, but you can make use of Firefox Safari or any of us, as well as this, you will also need a text editor. I will be using Visual Studio Code, which is available from code dot Visual Once you've downloaded this and open this up, you'll see a startup window just like we do on the left, but you can't use any other editor if you prefer. So let's now jump into the first lesson. We'll begin by creating our project. 3. Share Your Work On Skillshare!: When taking any course, it's really important to not get in the habit of following along just for the sake of ticking off another lecture. Take the time to process each lesson, review the code which you write, and think about how you might approach these solutions yourself. With this in mind, this class is project-based and this gives you the opportunity to really make something personal and unique. You don't need to get too lost and divert away from the class, and you can even take a step back after you've finished the class and come back and make some some changes afterwards. This will really give you a good chance to practice what you've learned away from the class. Also, remember to share your project too here on Skillshare and not only will I check it out, but it will also inspire fellow students too. More information on the class project, head into the project and resources tab, where you can not only upload your project, but you can also see other class projects too. With this in mind, I look forward to seeing what you create and upload here on Skillshare. 4. Project Setup & HTML: This is the final version of the game which we now go into Build. It will help you visualize exactly what we're going to create. The idea of this memory game is pretty simple. We have a sequence of squares with no background color. For each one of these has a hidden color attached to it. So when we click on any of these, it will reveal the color. And the idea is create a matching pair. Once we do, our score is increased. Small animation effects, and these two colors will remain on the screen. We then carry on by clicking on the additional squares and try to keep going until all of the matches are being created. So to do this, as ever, will jump into the desktop and create a new folder. I'll call this the memory game. Let's drag this over into Visual Studio code. Okay, and from here, we need to create our usual files to get started, we'll begin with the index page. So let's jump into our sidebar. Click on the new file icon or use Command or Control N. To create our index HTML page. We use the built-in shortcut command, which is HTML colon five, which will set up all of the boilerplate which we need for our index, is that the title of the memory game? And for this, the HTML content is pretty simple. All we're going to add if we look at the final version, is a title at the top, we'll create a element which is currently not visible, which will hold the score, will add a button which we can't currently see. This will be to play again. Control with JavaScript is putting will only appear once all of the matches have been created, allowing the user to restart the game. We'll also have our grid area, which will be an unordered list, and each one of our squares will be a list item. So pretty simple in terms of the HTML. So let's jump into the body section. We'll kick things off with a level one heading, which is going to be the text of memory game a p elements. And this is remember for our score, and we'll set this to an initial value of 0, placing a unique ID of skull. And we'll use this to grab this course section inside of JavaScript. We'll use it to show and hide this section when it's needed. And also to increase the score each time the user has a match. As mentioned, we'll also need a button and this is to play again. We'll also hide this until the game is over. And then if I was squares will create an unordered list. In the upcoming video, we'll create this unordered list to be like a grid. So for now it's going to be empty because we create each one of our squares using JavaScript also gives us a unique ID of squares. Save this, and then let's open this up inside the browser. So our options are either to go into the memory game folder and double-click on the index page to open this up. Or using Visual Studio, we can also right-click on the tab, copy the path, and paste this into the browser. Of course, this doesn't look great at the moment. We need to create our styling in the upcoming video. And we'll prepare for this by creating our new file to hold this in. So when you file, this is the styles dot css. And of course we also need a JavaScript file to control our game. So create a new file also inside of here. This is the scripts dot js. We'll come back to this at a later date, but for now we'll just jump into our index page, goes down the sidebar and we'll link to our two files. So first of all, in the head, we'll create our link to our style sheets. And since this is inside of the same folder alongside our index, we can simply references by the title styles.css. And then down at the bottom of the body section, just below the unordered list, create a link to our script. The source is just the filename of script.js. Let's check this is working with an alert. In any text inside of here. Save our file and refresh the browser. And our JavaScript file is correctly linked. We can remove this. Save all of our files, and we'll now move on to the next section where we'll create our styles to make our game look a lot nicer. 5. CSS Styling: Now it's your turn off our style sheets, which were created in the previous video. And idea is to make this look more like the final version. And of course you can tailor it to your own style to what I'm going to go too crazy. We're just going to create some basic styling and colors to make it look a bit more appealing. So to start, we'll jump into our style sheet and we'll target the body section. And we'll begin with the font family. So again, you can set up any colors and the fonts and sizes which you prefer. So select any one of the font families which you would like to use. To check this is linked correctly inside of our index. Give this a save and refresh the browser, and you should see a change to our text. Okay, next, we'll set the body to have the display type of flex. And this will allow us to set the flex direction to be column. This will give all of our content is vertical, stacked on top of each other layouts. So we'll have the title, we'll have the skull, which is currently invisible, the button which is currently invisible, followed by our unordered list. The display. Use the Flexbox. By default, the flex direction is going to be in a row, so everything will appear from left to right across the page. And we can change this by setting the default flex direction to be column. Place everything into the center, such as the text and the score. We can set the line items in the center. When using the flex direction of column. This will push everything down to the middle of the browser, the background. The background. I'm going to pick, we'll make use of a linear gradient, which is going to take in three different colors. With linear gradient, we can set the first section of our gradients to be the value of any angle we want this to appear. So we can change the color from the top left to the bottom right, from the left to right, from top to bottom or any other angle which you want to, I want to go for 90 degrees and then separated by a comma, placing three different colors. So the first one, this will be the starting color over on the left, which is an RGB value of 2015149. So this will start at the very beginning. So we'll place this at 0 per cent. Let's make a little bit more room so we can see this on the page. Okay? So we've got our first parameter, I will second one, and then another comma just after the 0 per cent. The second RGB value. Open the brackets. This one is 118248 to free 0. And then after this, just after this blue bracket, placing the percentage which is 50, will begin at this color. 50 per cent way through the gradients will have this color and then separated by comma, our third and final value. Again, an RGB value, which is going to be red, value of 70, green, and blue, 249. This is the final color. So this is going to be on the far right. So we'll place this at 100%. Refresh the page. We'll begin at 0, which is our darker color. We have our middle color. Then at 100%, we switch over to this third value, just after our background color, which will apply to the text. And this is going to be again, an RGB value, will place it in a value of 2073, then 63 for the blue. Also, just as a personal preference, I'm going to set some space in between each one of these letters with a value of two pixels, just to make the text a little bit more spread out. Okay, so after this, I'm going to leave the level one heading as it is. And we can move down to the score section and also the button from our index page. We have our score, which has the idea of score. Then we have our button just below. Stylesheets. Grab the score using the hash, since this is an id, will increase the font size to be two rems. The font weight to be a little bit darker. So this can be bold. Then some margin on the top and bottom. So one rem on the top and bottom. And we'll leave as 0 margin on the left and right. Next up, we have the button, which never looks good by default. So we'll target this with the button selector. And buttons don't automatically inherit the font family which was set from the body. So we can copy this same font family. Places in. This will change the button text. Okay, so what I want to do here is to remove the default border. We'll add some rounded corners. And we'll also set some padding to make it a little bit bigger. And it's also nice to change his cursor to be a pointer. So we'll start with the rounded corners using the border-radius of five pixels. Remove this black default border. By setting this to be none. Okay, it needs a little bit more spacing, which we can add padding. Remember the padding adds the space into the inside of the element. So if I add two values, the padding, the first value of 0.5 rems, we'll apply it to the top and bottom. And the second value will apply to the left and right. The font size to apply to the text of one RAM. Some letter spacing of one pixel, and change the cursor to be a pointer. So these last two properties will space out the text and also give us this hand pointer each time the user hovers over this button. So back to our index page. The next thing we have, the style is our unordered list. As we can see, we don't have any one of our squares inside of the unordered list to work with. So we'll begin by adding some empty list items just to simulate how this will look when we add these with JavaScript. So placing a list item and you can duplicate this as many times as you want to. Currently always see is these dots will go over to our style sheets and we'll begin to work with our unordered list. First of all, suddenly display type to be a grid. The grid will allow us to set out our squares just like we see in this final version. So we're going to set how many rows and how many columns we want, and also the size for each one of these squares. We do this by first setting the grid template columns and we can set as many values as we want to inside of here. So for example, if we add a 100 pixels and 200 pixels, this will give us two columns, the first one or 100 pixels, and then the second one of 200 pixels. But since we're going to be creating four different squares, which is equal size, we can make use of the repeat function. The repeat function is going to take in two things. The first one is the number of columns separated by a comma. The second value is the size of each one. So 100 pixels. And if we copy and paste this, we can change this to be grid template rows. This to close. We also want four rows or 200 pixels tall. This effectively gives us a four-by-four grid, leaving us with 16 individual spaces. And we'll see this more clearly very soon once we get onto the list item, the gap around each one of ten pixels. I will also remove the default padding value by setting this to be equal to 0. And then move down to the list item, list item. We need to move these dots. Are these bullets by setting the list-style to be equal to none. That gets rid of those. We'll set a border. And the thickness of the border will make this quite thin. So 0.5 pixels, a solid line color. The color of the line. We use an RGB value of 2036, which gives us our first row. And since we've only got four list items, is only occupy the first four spaces. Let's go ahead and duplicate these four items. Make eight. We now have space for eight different items and these will now appear on the second roll. Good, so to break the corners of each one of these squares, we can place in some border radius of ten pixels. And also set the cursor to be a pointer. Since we want the user to be able to click on each one of these. Good. So this is our basic styling for now. We will return back to this later and add some animations. Will set up two different animations. And the first one will be if the user gets the correct guess, I'm one if they also get it wrong. 6. Selecting Random Colors: Okay, so we've now got our index page with our markup, we've got our style sheet, and this is how our game is currently looking. We also have our script, which is currently empty and we're linked at the bottom of our index page. So the objective of this video is to create an array which will contain all of the colors which you want to use for all of our 16 squares will make 16 squares. So we need eight pairs of colors to create a batch. So for example, we have an array with two reds, two yellows, two blues, and so on. The second objective is to create a function which will randomly select one of these colors, will assign that color to a particular square, then that color will be removed from the array. So we don't have any duplicates. So first of all, step one is to create an array called colors and start eight pairs of colors inside of here. So jumping into our scripts, create our array called colors. And each one of these is going to be a string. So you can change these colors to be any different one you want to, you can also change it to be an RGB color, but I want to use a hexagon color as a string. So there's all just CSS values, so that begin with the hash. And the first value I've chosen is 3333. Separated with a comma will duplicate this one. So we have a pair because we want to make it 16 colors, but there'll be eight different colors to make pairs. After this, the second color, again, a hex color, will be double F9 will for D. And then duplicate this one. The third color, this is going to be a 0, C-C double F a comma, and duplicate this one. The next one. Double F, double six. Duplicates next double F4, D to duplicate. Next, double F on a, on a comma copy and paste. Whoops, don't forget the ashes at the start of each one of these. And the next one is going to be all of the d's. So 60 days. After this, we'll have 000099. Duplicates. Should be everything we need. We've got our first pair, 2345678 pairs there. So this gives us 16 different colors to each one of our squares. Next, just after this, we'll create a function. And the job of this function is to select a random color from this array, and then we'll remove it. So it starts, we'll just create our function body called Select Color. And to randomly select one of our 16 values from the array, we can create a random number containing 16 choices. So we use the map function, generates a random number. And we could, if we wanted to multiply this by 16, or instead, I'm just going to make use of the colors array and select the length property. So colors, the land. And if we do decide to change this in the future, this will automatically pick this up. Remember that Math.random gives us a random number between 010 is included, but the value of one isn't. It goes up to 0.999, for example. And what we need to do is to get some whole numbers so we can round this down. Let's cut out of place all of this access Math.floor paste in our random number. This is going to round this down. So this will give us a number between 015, resulting in 16 options. Store this inside of a variable or constant called random. I will just make a comment. So this is 0 to 15. And we can now use this random number to select any one of our colors on the colors array. So select colors. And just like with any other array, we can pass in an index number to select a particular color. But we're going to pass in our random value to give us a random selection. This inside of a constant called selected. Then after each one of these random values is selected, we can then remove this from our colors array of colors dot splice. Splice method will remove any one of our values. So first of all, the index number, which we're going to begin with. So if we start from here, we can even remove the single value or we can move every value just afterwards. So the starting position is our random number for our index position. And since we only want to remove one single value at time o, placing a value of one to only remove this single value. After this, return, our selected value. Then we can test this by calling our function just below. So I've called it by the name. We will call this twice so we can see how many of these values has been removed. Also placed in a console log for our colors array. Over to the browser and open up the developer tools with right-click and inspect. Jump into the console. Refresh. And we can see we've got an array containing 14 values. Remember that our original array containing that 16 values. We then run our function twice. And on each function call it removed one single value from a random position. Therefore, by the time it gets down to the console log two positions have been removed. Let's copy and paste. This should now result in 13 values. And removing one each time we've selected. It means we're going to be left with unique values. Will also do one more test, will cut out of place. One of our function calls, places inside the console log. Just remove the semicolon. And each time we now refresh, we should see one of our randomly selected array values. Good soul with our random value from our array now selected. Next we can use this random color inside of a loop to create the 16 squares we need to display for our game. 7. Creating The Grid Of Squares: Welcome to the next part. The objective of this video is to create a loop which is going to run 16 times. This in combination with the CSS which you already have in our style sheet, will be used to create our grid of squares, which we need 16 squares, which is four rows of Foursquare's. Also in addition to this, each one of our squares needs a custom attribute to store the color which it's supposed to be. Remember, we have all our hexagon values just here. We don't want these to apply to the background color of our squares, because obviously this would make the game pointless because the user will be able to click on the colors which they can see. We want to be able to hide these. So to do that, we'll remove the background color and we'll also store these as attributes so we know which one of our squares we can match up. Oops, while we're here, we'll also just add the hashtag, both of these two colors. So if you already haven't done so, we'll begin by going over to our index.html and we can move all of the empty list items which we created it just to see how it would look with the styling. So remove all of the list items, and then back over to our script. We'll start by selecting our unordered list from our index page, which has the ID of squares. The top. Create a constant to hold these in called squares container. We use querySelector. So document dot query selector. Passing how string, which is the hash, since this is an ID and the name of squares. I just create a little bit more space so we can see this all on one line. And then we'll create a variable stored in a constant called number of squares. We want 16 squares. And then another variable called I, which is going to be equal to an initial value of 0. And we'll use this for the while loop, which we're about to setup. Okay, so down to the bottom and just blow our select Color function, which we're going to use in combination with our loop. We'll make use of a while loop. This will run while I is less than the variable called number of squares. So remember the I is currently equal to 0 and number of squares is 16. So effectively this will begin by running and we'll say, while number 0 is less than 16, run the code inside. And then before I forget, we'll run I plus, plus. This is going to increase the value of I on each loop. To begin, 0 is less than 16. So the code inside will run, will then increase I to be equal to 11 is still less than 16. So the code will keep running it 16 times. But what code do we need to run inside of here? Well, since we have in our index page and unordered list, and it seems we've selected our unordered list. At the very top. We're going to create a list items to place inside. And these are just like the list items which we added inside of here. So it's create these with JavaScript. We use document dot create elements, passing the tag name of LI to create a list item, and then store this inside of a constant called square. Okay, so now we've got the container and we also need a random color. For this, we've got our function above called Select Color. And this is going to return a selected value from our array. Store this inside of a constant called color, which is equal to the return value of our function called select color. We can also remove or comment out this code from below. And we'll check this is all working by adding these colors to our squares. So access r squared, which is the list item. We can set the style background to be equal to o random color. Okay, so now we've got our list item which we're creating. We can now add this to our squares container. Can do this by accessing a pen child. So access the container or the parents gold squares container. The append child method to add our new list item, which is the variable called Square. Refresh. This now creates I was 16 list items and we've set the background color to be equal to o random values. I remember it since we're removing each one of these random values afterwards, we only ever see two of each one of these colors. Good. So we've got these squares which we want, but we don't actually want to see the background color like this. We'll comment this out and instead will access, each one of our squares. Will set the attribute, which is going to be equal to a custom attribute called data dash color. The value is going to be equal to our color. This extra piece of information or this attribute is going to be added to each one of our squares. So we can see this if we go into the developer tools, right-click and inspect elements, jump into the body section, open up the unordered list. And we're going to see that each one of our list items that we created has this custom attributes with the hexagon color. 8. Listening For Clicks: Now how about 16 squares on the screen? We're now going to add an event listener to each one of these squares, which will trigger a function when clicked on, the game will be played in pairs. So i e, when we click on two squares, we're going to compare the colors of each one. This we need to store the color of both the clicked on squares and then track if it's the first or the second selected square. Phones compare both of these only if it's the second click. So if we've got two selected squares, will compare the colors of both of these. So to start, we'll jump down to just below our while loop. What we're going to do is to select all of our squares which are stored in the list items. So grab all of these, would query selector all loop over these, and then add an event listener. So saw these inside of a constant called squares will then make use of document dot, query selector. All will select all of our list items. This is going to contain a reference to our 16 list item squares. Then below this will make use of a for, of loop to loop over each one of our squares and add an event listener. So a for, of loop starts off just like a for loop. Inside of here you will say const square of squares. This means we'll loop over all of our squares, which is our 16 list items. And then we can access each one individually with this square variable. So access our square dots add event listener wants to listen out for a click on each one of these, which will run a custom function called square clicked. Okay, So just before we create this square clicked function, we're going to go up to the very top and add a couple more variables to store the information which we need. The information which we need is the two kicked on squares. So it will start playing. We'll click on the first one and then we'll click on the second one. I install these inside of two variables. So let's square one. Separated by comma will also create a variable called square to. These don't need any initial value. And also since we only want to click on two squares at a time, we're going to keep track of this with a variable called click count, which will be equal to 0. Equal to 0. We'll click on the first square. This will then be increased to warm up. Click on the second one, this will be increased to two. We'll check if as much. And then we'll reset this back to 0, stopping the user clicking on a third square. Okay, So back down to our function which we need to create, which is called square clicked. Let's set this up, but just below. As mentioned, for each one of these clicks, we need to increase our click count variable. We'd plus plus. So this click on variable is going to be really useful because we need to know if it's the first or the second square which we are dealing with. The first click is going to set our square one variable. And the second click we'll set our square two. Is it going to hold all information from our list item which were created, including the attribute containing the color. But just before we do this, how do we find out which square has been clicked on? One way to do this, which you may have seen it in the past, is to pass the event information into the function. And we can access this with E dot targets. Or another way is to access something called This. Will see the value of this. If we pass this into a console, log, save and refresh. Jump into the developer tools into the console. Okay, So click on any one of our squares. We can see a list item or click on a second square, our second list item. Both of these point to different data attributes. So the this keyword, it can be a complex thing in JavaScript, mean different things in different contexts. But for our use case, we can see it logs the value of the list item which we clicked on. So we can use this to set our variables. We can do this with a JavaScript conditional operator. The conditional operator, often referred to as the ternary, will ask a question, will say, is the click count equal to one? Ask a question if it is equal to one or wants to do is to set the square one variable to be equal to this. Or if not, if this is equal to two, we'll set square to be equal to this, setting our two variables. And don't worry, if you save on Visual Studio code automatically adds in these brackets. This is completely fine. Okay, so to test this, we can place in a console log the value of square one and then square to refresh and open up the console. Click on the first one. We can see since we've only clicked on one, the first square one variable is set and the second one is still undefined. Click on any of the square, will get the value of two different list items. As we know, all of our squares are just currently an outline. I will need to reveal the background color when each one of these is clicked on, let the user know which color it actually was, so they couldn't remember it for next time. So to do this, we'll pass in an if statement, remove the console log. And we'll say if the click count is equal to one, so the first square has been selected. What we'll do is we'll grab our first square variable. We'll set the style dot background. Remember this is just what we did as a temporary measure inside of our while loop to set the colors. We'll set this equal to square one. We'll grab our attributes, which we set here, where it gets attributes. Attributes which you want to select is this custom one called data color. Pass this in as a string. If not, this is equal to our second clicks or pass it in l statements. Copy this line of code. I don't want to do here is to change this to be equal to square root two. So just as a recap or first clicking on any of our squares, we're running, our function will increase the click counter be equal to one. If this is equal to one. Or set square one to be equal to the clicked on list item. If not, it's the second click where we'll set square to. Again, checking if the count is equal to one. The first square is being clicked. We'll change the background color to be equal to the data color attribute, which is stored inside of the list item. If it's the second click, we'll set this equal to the square two color. So both of these will be revealed in our game. Let's try this. Refresh. Click on the color. And square one has his background set to be equal to our attributes. The second one, both of these colors are now set correctly. You will notice all we can keep going and clicking on the rest of the colors, even though we only want to deal with it two at a time. But this is something we will deal with in the future. Next, we'll handle what to do if the colors are much or if they are different. 9. Checking For a Match: As the title of this video suggests, the objective now is to wait until two squares have been selected. And then we can check if they are a match I, II, they both have the same color attributes. This will go down to r squared clicked function. And inside this function, the L section will run if two squares are selected. So I click count is equal to two, then the else code will run. So this is the place to check if there is a match and we can add the code directly inside here. Are instead I'm going to create a separate function. So this function is going to be called cheque match, which will now create. So go just below our square click function and create this function. Check match. So how do we actually go about checking if both of these are a match? Well, the way to do this is to access square one and square to just like we did above. We'll use the get attribute method to cover the value of each one of the colors. We can then check if these are equal and store them inside a variable. Just like we did here. X is our variable called at square one, will get the attributes, which is called Data color. And we'll check this is equal to this same using square two. So this is going to compare both for attributes and this will return a Boolean value of true or false, which we can store inside a variable called match. Then the value of match will determine which on to the next functions we're going to run. So we're going to create two new functions. The first one, if there is no much, then this one is going to be, if there is a match. To determine which one is going to run, we can place in an if statement. Inside here, we'll check if there is no much, which will run if this is equal to false, then we'll run our matching function and cold know much else will run our second function. And in fact we'll call this is much just changes. One is much. So only one of these functions will run at once. And we'll, we'll come back to the majority of this content in the upcoming videos. But for now, what both of these needs is to reset to click count. Since both of these are only run if we're on the second click. So that means we have two squares selected. So we need to reset the click counter, be back to 0. So let's first do this. Click count is equal to 0 and the same is a match. Now we'll, all we'll do inside of both of these functions is to place in a console log to check this is working. The first one of no match. The second one is a match. Okay, Let's test this out. Refresh the page into the console. First of all, we'll click on any two squares. We can clearly see because of the color of these and not a match. And the correct function has run. So we'll try to create a match. This one is still not much. But if click on our two greens, this one is going to be a match. 10. Handling a Match: At the moment, we can click on any number of squares and the colors are then revealed. We need to limit this to only work with two squares at a time. So we don't see what we're currently have. Previously, we created two functions, which is to handle the match and the note match conditions. All we do is increase the click counter on each one and do a console log for testing purposes. All do now is extend these functions to deal with these outcomes, starting with the note match function. So if there is no much wants to do, for example, just here is we want to select two of our squares and then if they aren't much, we need to then flip them back over to effectively hide the background colors. So to do this, just above our click counts, what we'll do is we'll access both of our squares. Drop the style property, where we'll set the background to be equal to an empty string. We'll do the same for square number to save this, and let's try this out. We didn't know much. So click on any of these. And we can see as soon as you don't have a match, this one is so that's fine. We don't have a match like this. The second one disappears so fast that we can't see what color it was. Now, this isn't good for our game because the idea is we want the users to be able to click on these colors. I don't remember which one was which. So to slow things down, what we can do just before the call are no match function. We can wrap this function call with a timeout. Let's cut this out. Place in a JavaScript setTimeout, which will run a function. This function separated by comma will run after a certain amount of time. So this is in milliseconds. So 500 milliseconds is half of a second. And then inside of the function body, paste back in our function call. Reload the browser and let's try this out. Let's go for the payer which doesn't match. We can see both of the colors is revealed, and then they wait 2.5th before removing. This gives the player a chance to remember which color was selected so they can use it in the future. So we can then start to compare our next pair of squares. What we're then going to do just above the click counter is to also reset square one. Reset the variable to be a string or rather an empty string. And we'll do the same for square two. Given us a blank canvas to work with for our next try. So this is all we need for our no match function. So down to the is much function which is going to run if two colors are the same. So what we're going to do it if there is a match we already set in the background color. So we're going to remove this border which we already have, and also remove the event listener so it doesn't interfere with the rest of the game. Just above the click count. Grab the square one. The style property. Well, we'll set the border to be equal to non. Copy and paste this. Do the same square to. Next, we'll remove the event listener so we can no longer right-click on these squares, which will interfere with the rest of the game. Square one. This time we'll call remove event listener. And this needs to take in the same parameters as one of the first setup, this event listener. So if we go up to the event listener section, which is just here, we need to pass it in the exact same parameters. So this includes the type of event listener which is currently click, and also the function which is to be called. I'll paste this in. Copy and paste square two. Now let's try to solve it by finding a much dark blue orange. We have two oranges. So let's click on this, this form, we have a match. These remain in the game and we can see if we look closely, we don't have this border surrounding each one. Let's click one of these revealed squares. Now for click a second one. Since the event listener has been removed from the first one, we're still need to click on another square to make a pair. So things are starting to work as they should now, but there is some small issues we need to resolve. One of them is dealing with clicking on the same square twice. If we were to do this and click on the same square twice, just like we've done here. We can see the board has been removed and this is considered a match since obviously they both have the same data color attribute. To fix this, Let's go up to our square. So this is run each time I click on any one of our squares on the grid, we can jump into our function and add an if statement. And this if statement is first going to check if the square one is equal to this. So what this means is if we've already clicked on one square, this will be equal to square one. And then when we click on a second square, again, if I click on the same one, this will be equal to alpha square. If this is the case. We'll then return out of this function before running any further code. Another issue is we can also quickly click on More than two squares. So jumping click 123. And before the 2.5th delay has completed, click on More than two squares. So for this, we'll do something very similar will return out of this function if something is true. But this time we'll do it just below our click count. We do this because if we currently have two squares clicked, the clicked card will be equal to two. So therefore, we can place in an if statements, which is going to check if the click count is greater than the value of two, then we'll return again, alter dysfunction. Let's test this. Refresh when Click on the same square multiple times and it doesn't have any effect. We can quickly click on More than two squares. More than two clicks is ignored. 11. Tracking The Score & End Of Game: The objective now for this video will be to keep track of the score and make use of these p elements, which we created in an earlier video. We're going to update this each time we have a match, will also hide it when we don't have any current score. Also, once the game has ended and all squares are matched with a handle this and let the user reset the game to start over. So to begin over in our script, what we're going to do is to create a new variable to keep track of the score. Will use lessons. We can update this and we'll initially set the score to be equal to 0. As mentioned, we don't want this to be shown as 0 before the game starts. So we can hide this by accessing the document. Query selector. Remember, that is p elements which displays the score, has this idea of score. So we can grab this as a string. Set the style dot visibility be equal to hidden. So the reason why we're going to toggle the visibility rather than the display type is because we want to also keep this space inside of our code. If we set the display to be none, this will then remove this element from the browser and push up all the games that the very top. And also, when we do reinstate this to display the score, this would then push all the game down and make it look very jumpy. Ok, so now we need to update the score variable and also reinstate this. We have our first match. So go down to the match function, which is just here. Stefan is to call score plus plus increases by the value of one. We'll use document dot query selector to grab our Scott elements and we'll set the inner text to be equal to our score. That's also copy and paste this line. Grab all p elements once more. This time we'll set the style dot visibility to be equal to visible. This will an override the hidden property which we set at the top. So let's save this and try this out. Initially, when we first reload the game, the score has been removed because we set the visibility to be equal to hidden. Now when we refresh, Let's try to get much. I've got two pinks. I will score is now updated. Next we're going to create a new function which is going to check if the game has ended. And this means that all of all pairs has been matched. So for this new function, which is called check game ended, and we'll run this function each time we have a matching pair. So we need to know exactly what causes our game to be over. So this is going to be our number of squares, which is set to 16. And then divide this by two. Since we're matching these impairs. Save this inside a variable or a constant called target. So this result is effectively eight. We then need to create a second constant, which is going to be a Boolean value called GameOver. We can make use of the JavaScript conditional operator. So we'll check if the score is equal to or above target. Ask the question. If this is true, GameOver will be equal to true. So basically, if the score is equal to eight, will return true. If not, we'll save the value of false. We can then run an if statement to check if game over is equal to true and then run some code inside. So inside this if statement will want to do is to reset up a game displaying this play again button. Currently we have not yet hidden it. So we'll come back to this in just a moment. Now what we'll do is to run our function inside of the cheque match function. So check much. This is run each time we'll have a pair of square selected. And we only want to check this if we have a match. So just after we've checked if there is a match, will then run this function. So as mentioned, if this is true, this is going to trigger our Play Again button. So first we need to hide this before the end of the game. Let's jump up to the very top. Grab this, install this inside of a constant called Play Again button. I'll grab this with documents dot query selector, string. If we go over to our index page, we can see this doesn't have any classes or IDs. So we can grab this simply by the tag name of button. Will access this variable, will set the style dot visibility be equal to a1. This means as soon as we refresh the page, we don't see the button. So once the game is over, we do need to do the opposite of this by setting the visibility to be equal to visible. But just before we do this, we'll also access our Play Again button. We'll add an event listener, which is going to list now for a click and run a function called play again. Okay, so now to round things off, what we're going to do is set our button to be equal to visible once the game is over. And also will create this play again function. Let's start with the visibility. Go back down to our check game ended function. So if the game is over, if this is equal to true, will access all play again button and do the opposite by setting the style dot visibility to be equal to visible. Then finally, we're going to move this commented out code and create our function which runs each time I click on the button. We added the event listener for this and call this play again. The code for this is going to be pretty simple. All we're going to do is to reload the page by selecting the window dot location and then calling the reload method. Save this and refresh the page. So what we need to do now is to complete the game by matching up all of these squares. The gray, green, light blue. There we go. So as soon as the game ends with NCD play again button, click on this. This calls the reload method and then restart the game. 12. Animations: To finish off the project, we can now add some animation effects. There will be a shake animation if the match is incorrect. And for a correct match, we'll add a pop effect. So for this, let's go over to our style sheet and we can add our animations inside of there. So down at the very bottom, what we're going to do is first setup two different classes, which we can insert with JavaScript. The first one is if the match is incorrect, want to make both of these squares do a little shake. So for this, we'll add an animation effect. We'll call it a shake. And we'll set this up in just a second. I will make this happen over 0.1 seconds. So it'll be really fast shake, and then the squares will reinstate back to normal. If the match is correct. We'll do a pop effect. Just like above. We'll create our animation which will be called POP, will make this a little bit longer. This will be over 2.5th. So for both the shape and also this pop, we need to set up the keyframes. So we do this with add keyframes. I'm passing the name of shake. So inside of these key frames, what we do is we want to set up the various stages of the animation. So we can set this up from the beginning to the end, or we can also add different stages as we go. So for example, at 0%, the animation can be a certain state, then twenty-five percent, fifty 75% percent, and finally, 100 per cent. So if you've not used these keyframes before, all we need to do inside of these curly braces is to add any one of our CSS properties. And we can change these are different states. So for example, we could maybe say some color to be one color inside of here. Just say color red. And then at twenty-five percent, we could change this to be colored blue. And this works for any one of our CSS properties. But for our case to make the shake effect or wants to do is to use the rotate, which is going to rotate the elements by a certain amount of degrees. So to do this, it sets up a transform called Rotate. And since this is the very beginning, we'll set this to be 0 degrees. Let's copy this section. Paste this in it to twenty-five percent. For this negative three degrees, halfway 50 per cent will reinstate this back to the middle. This will rotate negative, and then back into the center. Three-quarters the way through, we'll add this as a positive value of free degrees. And then at the very end, we'll reinstate the square. So all of this is going to happen really quick since we've set this to happen over the duration of 0.1 seconds. So we'll quickly rotates to the left and right and then place a square back into the center at 0 degrees. The next one, the pop effect. We'll do a similar thing. We need to set up the keyframes with the keyframes rule. This one was called pop. So 0%. For this one, it doesn't need as many stages. All we're going to do is to scale up the elements to make it a little bit bigger, and then scale it back to the regular size. So we need three stages, the beginning, the middle, and also the end. So if this will also make use of transform, this one is going to use scale. So when we use scale, the value of one is irregular size of the element. So this is effectively the starting position. Let's copy this. And we want to make this a pretty subtle effect. We can make this twice the size of three times the size or anything which you want to. But all I'm going to do is make a little subtle pop, which will make the element a little bit bigger and then reinstated back to its regular size. The value I want to go for is 1.06. Then at the end of the transform, this back to the regular size. This will all happen over the duration of 2.5th. So back to our script. First, deal with if there is a match, we'll add the pop class down to the function. Just to, Yeah, And then all we need to do inside of here is to add the class of pop. So let's add this. Just after we set the visibility access square one variable. The class list. We use the add function to add our class of pop, copy and paste this, and then change it to be square root two. So I'll pop class added and we also need to add the shape class. So to do this, we'll go to our function where we check the match. Remember inside of here we have our two sections. The first one is where we check if there isn't a match. If there is no much. Just before the timeout, we can access our square one. Dot class list. Dot add will add the shake effect. Duplicate this square two. So here we add the shake effect. We then wait 2.5th, call the no match function. And then inside of the match function, we can then remove this shake effects. So go down to the no match function. Okay, this inside the figure. So we remove the shape class because the squares can be wrong multiple times. So adding and removing the class will trigger the shake effect on each attempt. So let's do this weird square one dot class list. But this time we'll call the remove function. Jacque will also do the same for square two. This should now be added and removed. So if this class was only added and never removed, it will only ever be called once. So for example, if we had an incorrect much just like this, next time we tried to make the incorrect match, wouldn't get the shake effect. Okay, So make sure all of the files are saved. Let's refresh the page and we'll begin. This is an incorrect match. So we can see we have this shake effect, which is really fast and it's over the duration of 0.1 seconds. Let's try the pop effect by creating a match. Greens. Now when we have a match, we get this pop effect which makes the elements a little bit larger and then returns back to the regular size. 13. Follow Me On Skillshare!: A huge congratulations from me for reaching the end of this class. I hope you really enjoyed it and gain some knowledge from it. If you've enjoyed this class, make sure you check out the rest of my classes here on Skillshare and also follow me for any updates and also to be informed of any new classes as they become available. So thank you once again, good luck, and hopefully I'll see you again in a future class.