Event handlers review
Lets review our understanding of event handlers by updating the sample code.
<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>.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.logthe variable?Modify the above example to have one
turnGreenWhenClickedfunction that usesevent.targetto 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
turnGreenWhenClickedfunctionChange it back to an inline function - do we need to use
event.targetanymore?
Passing around elements as variables (pass into function, return from function)
Make a
turnGreenfunction, 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
Last updated
Was this helpful?