Skip to content

Instantly share code, notes, and snippets.

@yi-mei-wang
Last active October 4, 2019 06:13
Show Gist options
  • Save yi-mei-wang/ce0eb81a0032cb1e9d7bc571210ff904 to your computer and use it in GitHub Desktop.
Save yi-mei-wang/ce0eb81a0032cb1e9d7bc571210ff904 to your computer and use it in GitHub Desktop.
How to get started with tic-tac-toe, JS version

Some key functions to use when building the tic-tac-toe logic

Selecting elements

  • We select elements because we want certain parts of the web page to do some thing.
  • Once we select them, we can then perform some action on them, such as change the style, add child elements (such as using append())

Returns one element

  • document.getElementById()
  • document.querySelector()

Returns more than one elements (HTMLCollection of NodeList)

  • document.getElementsByTagName()
  • document.getElementsByClassName()
  • document.querySelectorAll()

Note: We know these are functions(sometimes called methods) because of the brackers at the end

Detecting user interactions

  • Every interaction is known as a user action or event. We want to detect these events because sometimes we want to do something in response to these events.
  • For example, when the user clicks on one of the grid, we want a marker to show up inside the grid.
  • The click is an event, while the marker showing up is a response.

How do we know if the user has performed a certain action?

  • As mentioned just now, we want to know if the user has done something, or as the programmers say, if an event has occurred.
  • We would use addEventListener() to detect these changes.
  • addEventListener() would wait for the specified event(such as a click, or when a key is pressed) to happen, and then perform some action (such as inserting a marker).

__Tip: console.log(event) when you're building the game to see what event gives you.

Some common events that we can listen to in JS

  • click
  • submit
  • mouseenter
  • mouseleave
  • keydown

You probably won't use all of the above events.

Adding/removing elements to the page?

  • Now we can select elements and know when an event occurs. In tic-tac-toe, we will also need to add/remove elements to the page.

  • In our case, an example would be to insert a marker.

  • Some methods we can use are:

    • append() & appendChild()
    • remove() & removeChild()
  • If you have time, I want you to find out what's the differences between the both of them.

  • Attributes we can change:

    • innerHTML
    • style
    • classList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment