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;
}
index.js
const square1 = document.getElementById("square1");

square1.addEventListener("click", (event) => {
  if (square1.style.backgroundColor == "green") {
    square1.style.backgroundColor = "white";
  } else {
    square1.style.backgroundColor = "green";
  }
});

const square2 = document.getElementById("square2");
square2.addEventListener("click", (event) => {
  if (square2.style.backgroundColor == "green") {
    square2.style.backgroundColor = "white";
  } else {
    square2.style.backgroundColor = "green";
  }
});
  • 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

myTimeout = setTimeout(function, milliseconds);

Example

Try running the following code in your browser console

setTimeout(() => console.log("Hello world!!"), 5000);

setInterval

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

Syntax

myInterval = setInterval(function, milliseconds);

Example

Try running the following code in your browser console

setInterval(() => console.log("Hello world!!"), 5000);

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