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 use the same callback for multiple HTML elements.
This video doesn't have any notes.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
How did you do?
0:00
I copied both nameInput events and
pasted them down here and
0:01
replaced nameInput with messageTextArea.
0:07
While this is fine,
we have some repetition in our code.
0:12
We have the focus handler twice and
the blur handler twice.
0:16
We can remove the repetition by
moving these event handlers into
0:24
functions with names.
0:28
I'll create two variables,
0:30
const focusHandler and const blurHandler.
0:34
Now we can move the handlers
out of the addEventListener and
0:45
assign them to the appropriate
variable names.
0:50
Now we can pass in the names of
the functions as callbacks to
0:56
the addEventListener method calls.
1:00
Avoiding repetition in your
code is referred to as DRY or
1:23
don't repeat yourself.
1:27
Look for opportunities for
sensible places to avoid duplicate code.
1:29
As you practice this will
become more natural to you.
1:33
Our code has one function to
handle all the focus events
1:37
or the input and the text area elements.
1:42
And another function that
handles all the blur effects.
1:48
Remember addEventListener will pass
in an event object to the callback.
1:53
The event object has an associated target.
1:59
Remember that the addEventListener
will pass in the event object with
2:03
the associated target element for
the event if the focus event
2:07
is triggered on the input,
then the event.target will be the input.
2:13
If the focus event is triggered
on the text area element,
2:22
the event.target will be the text area.
2:26
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up