Connecting the thumbnails to your event handling code will be short and sweet. You will write a function that will be the starting point for all of Ottergram’s logic. Other programming languages have a built-in mechanism for starting an application, which JavaScript lacks. But not to worry – it is easy enough to implement by hand.
Begin by adding an initializeEvents function at the end of main.js. This method will tie together all of the steps for making Ottergram interactive. First, it will get the array of thumbnails. Then, it will iterate over the array, adding the click handler to each one. After you have written the function, you will add a call to initializeEvents at the very end of main.js to run it.
In the body of your new function, add a call to
getThumbnailsArray and assign the
result (the array of thumbnails) to a variable named thumbnails
.
... function getThumbnailsArray() { ... } function initializeEvents() { 'use strict'; var thumbnails = getThumbnailsArray(); }
Next, you need to go through the array of thumbnails,
one item at a time. As you visit each one,
you will call addThumbClickHandler
and pass the thumbnail element to it. That may seem like
several steps, but because thumbnails
is a
proper array, you can do all of this with a single
method call.
Add a call to the thumbnails.forEach
method in main.js
and pass it the addThumbClickHandler function
as a callback.
... function initializeEvents() { 'use strict'; var thumbnails = getThumbnailsArray(); thumbnails.forEach(addThumbClickHandler); }
Note that you are passing a named function
as a callback. As you will read later, this is not always a good choice.
However, in this case it works well, because
addThumbClickHandler only
needs information that will be passed to it when
forEach calls it –
an item from the thumbnails
array.
Finally, to see everything in action, add a call to initializeEvents at the very end of main.js.
... function initializeEvents() { 'use strict'; var thumbnails = getThumbnailsArray(); thumbnails.forEach(addThumbClickHandler); } initializeEvents();
Remember, as the browser reads through each line of your JavaScript code, it runs the code.
For most of main.js, it is only running variable and function declarations.
But when it reaches the line initializeEvents();
, it will run that function.
Save and return to the browser. Click a few different thumbnails and see the fruits of your labor (Figure 6.28).
Sit back, relax, and enjoy clicking some otters! There was a lot to work through and absorb while building your site’s interactive layer. In the next chapter you will finish Ottergram by adding visual effects for extra pop.
18.191.234.150