Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
In this video we'll explore callbacks that can take arguments.
Callbacks are limited to
functions with no arguments.
0:00
Callback can have any number of arguments.
0:04
For example, this callback
function has one argument and
0:06
this callback can take two arguments.
0:11
Merge the workspace with this video We
have three div elements on the webpage.
0:14
In the accompanying JavaScript file,
we're selecting the elements and
0:23
storing them in variables.
0:27
Div1, div2 and div3.
0:29
Below, we have three functions.
0:32
One called make red,
0:34
that applies the background color of
red to an element that is passed in.
0:38
The make blue function applies
the background color of blue
0:44
to the element passed in.
0:48
The third function takes in an element and
the callback function.
0:50
It calls the callback and passes in
one argument, which is the element.
0:55
Into the callback function and
executes the callback.
1:02
Let's use makeRed and makeBlue as
callbacks to the addStyleToElement
1:06
function, and
apply those styles to div1 and div2.
1:13
Call addStyleToElement And
pass in div1 as the first argument.
1:18
The second argument can be makeRed.
1:27
What happens in this code is,
1:32
makeRed becomes the callback function
in the addStyle element function.
1:34
And div1 becomes the element.
1:41
The maker at callback is then
invoked with the element,
1:46
div1, being paste in,
applying the color red to div one.
1:51
Save the file and
see if it works, it does.
1:55
Let's do the same for div2 and makeBlue.
2:02
Save and preview.
2:15
Now we see we have a red div and
a blue div.
2:19
Here's a challenge for you.
2:23
Create a function to create
a makeGreen callback function and
2:24
then apply it to div3.
2:28
Pause the video and
I'll show you what I did when you resume.
2:30
How did you do?
2:35
I first created a function
called makeGreen.
2:36
I pass in an element and
then apply the background color of green.
2:40
Finally, I used the addStyleToElement
function and passed in div3 and
2:44
the makeGreen callback.
2:49
I could have easily just called
each of the functions directly, but
2:51
I wanted you to get used to using
callbacks with one argument.
2:55
Using callbacks like this
will become more important
2:59
when you see them in use in
the DOM waiting for events.
3:01
We'll explore that next.
3:05
You need to sign up for Treehouse in order to download course files.
Sign up