Event handlers review

Lets review our understanding of event handlers by updating the sample code.

index.html
<html>

<head>
  <script src="index.css" async defer></script>
  <link rel="stylesheet" href="index.js">
</head>

<body>
  <div id="square1" class="square"></div>
  <div id="square2" class="square"></div>
</body>

</html>
index.css
.square {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  margin: 5px;
}
  • Passing around a function as a variable

    • Copy the function to a new variable name and then call it

    • What do you see when you console.log the variable?

    • Modify the above example to have one turnGreenWhenClicked function that uses event.target to determine what was clicked.

    • What if I rename the variable something other than event?

  • Make it a loop using document.getElementByClassName('square')

    • Use the same turnGreenWhenClicked function

    • Change it back to an inline function - do we need to use event.target anymore?

  • Passing around elements as variables (pass into function, return from function)

    • Make a turnGreen function, pass in the element you want to turn green

Timer functions

setTimeout

The setTimeout() method calls a function after a number of milliseconds. It will be called only once.

Syntax

Example

Try running the following code in your browser console

setInterval

The setInterval() method calls a function at specified intervals (in milliseconds).

Syntax

Example

Try running the following code in your browser console

circle-info

Now that we have an understanding of how timer functions work. Lets try updating the code to clear the green color from the element after a fixed amount of time.

Last updated