Event handlers review
Lets review our understanding of event handlers by updating the sample code.
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 usesevent.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
functionChange 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
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
Was this helpful?