6
Handling Events with JavaScript

You know what is cool about otters? Among other things, they hold hands when they sleep so that they do not float away. Keep this image in mind as you learn to work with event callbacks in JavaScript.

JavaScript is a programming language that adds interactivity to websites by manipulating DOM elements and CSS styles on a page. It was originally created for use by people who were not professional programmers. It has grown in power and popularity and is now used for many kinds of application development. When you use sites like Gmail or Netflix, you are interacting with programs written in JavaScript. In fact, the Atom text editor is actually a desktop application written in JavaScript.

Despite its power and widespread use, it has its quirks, like any programming language. As you continue working on Ottergram and the other projects in this book, you will learn to navigate the rough patches of the language and to take advantage of its best parts.

There are several versions of JavaScript, and you will use three of them for the projects in this book. They are all revisions of a standard specification known as ECMAScript (or “ES”). Table 6.1 summarizes them.

Table 6.1  JavaScript versions used in this book

ECMAScript
Edition
Release
Date
Notes
3 December
1999
Most widely supported version; encompasses most of the language features you will use, such as variables, types, and functions.
5 December
2009
Backward compatible, with opt-in enhancements such as a strict mode that prevents the usage of the more error-prone parts of the language.
6 June
2015
Includes new syntax and language features; at the time of this writing, most browsers do not yet support ES6, but ES6 code can be translated into ES5, making it usable by most browsers.

In this chapter, you will use JavaScript to make Ottergram interactive: The detail image and detail title will change when the user clicks or taps one of the thumbnails.

To do this, you are going to write a JavaScript function – a set of steps for the browser to follow – that reads the URL for an image and shows it in the detail area. Then you will ensure that this function is run when a thumbnail is clicked. You will also write a separate function that hides the detail area and run that function when the Escape key is pressed.

At the end of the chapter, Ottergram will be able to feature any otter in the detail image (Figure 6.1).

Figure 6.1  Clicking thumbnails changes detail image and title

Clicking thumbnails changes detail image and title

As you write these functions, you will interact with the page using a set of predefined interfaces built into the browser. There are a large number of them, and the code will only walk you through the ones necessary for the task at hand. If you are curious, you can find more in-depth information about them on the MDN at developer.mozilla.org/​en-US/​docs/​Web/​API/​Element.

Preparing the Anchor Tags for Duty

Before you start adding interactive features with JavaScript, you need to make a few updates to the markup. Your thumbnail images are wrapped in anchor tags, but those tags do not actually link to any resource. Instead, they use the # value for the href attribute, which tells the browser to stay on the same page. In order to make a click on a thumbnail do anything interesting, you need to fix that.

First, in index.html, remove all but five of the .thumbnail-item elements. You no longer need the duplicates, because your layout is in good shape.

Then, change the anchor tags’ href properties to no longer use the dummy value #. Instead, set the values to be the same as each <img> tag’s src value.

Atom can help you make these changes, taking the tedium out of working with HTML. Like any text editor, it has a way to find and replace text. Select FindFind in Buffer or use the keyboard shortcut Command-F (Ctrl-F). This will open the Find in Buffer panel at the bottom of the editor window (Figure 6.2).

Figure 6.2  Using Atom’s find-and-replace feature

Using Atom’s find-and-replace feature

Enter # in the Find in current buffer text box and img/otter.jpg in the Replace in current buffer text box. Then click Replace All in the lower right.

This will change all of the <a href="#"> tags to <a href="img/otter.jpg">. Now it is just a matter of manually adding the appropriate number to each one (img/otter1.jpg, img/otter2.jpg, etc.).

Press the Escape key to close the Find in Buffer panel. index.html should look like this:

...
      <ul class="thumbnail-list">
        <li class="thumbnail-item">
          <a href="#">
          <a href="img/otter1.jpg">
            <img class="thumbnail-image" src="img/otter1.jpg" alt="">
            <span class="thumbnail-title">Barry</span>
          </a>
        </li>
        <li class="thumbnail-item">
          <a href="#">
          <a href="img/otter2.jpg">
            <img class="thumbnail-image" src="img/otter2.jpg" alt="">
            <span class="thumbnail-title">Robin</span>
          </a>
        </li>
        <li class="thumbnail-item">
          <a href="#">
          <a href="img/otter3.jpg">
            <img class="thumbnail-image" src="img/otter3.jpg" alt="">
            <span class="thumbnail-title">Maurice</span>
          </a>
        </li>
        <li class="thumbnail-item">
          <a href="#">
          <a href="img/otter4.jpg">
            <img class="thumbnail-image" src="img/otter4.jpg" alt="">
            <span class="thumbnail-title">Lesley</span>
          </a>
        </li>
        <li class="thumbnail-item">
          <a href="#">
          <a href="img/otter5.jpg">
            <img class="thumbnail-image" src="img/otter5.jpg" alt="">
            <span class="thumbnail-title">Barbara</span>
          </a>
        </li>
      </ul>
...

Next, you need to add additional properties to your anchor elements so you can access them using JavaScript. When styling with CSS, you use class name selectors to refer to elements on the page. For JavaScript, you use data attributes.

Data attributes are just like the other HTML attributes you have been using except that, unlike attributes such as src or href, data attributes do not have special meaning to the browser. The only requirement is that the attribute name starts with data-. Using custom data attributes lets you designate what HTML elements on the page your JavaScript interacts with.

Technically, in JavaScript, you could access elements on the page using class names. Likewise, you could use data attributes in your selectors for styling. But you really should not. Your code will be much more maintainable if your JavaScript and your CSS do not rely on the same attributes.

Update your anchor tags in index.html with data attributes. Note that the line breaks in the code below have been added to make sure that everything fits nicely on the page. You are free to add them or not, as you prefer. They will not make a difference to the browser.

...
        <li class="thumbnail-item">
          <a href="img/otter1.jpg" data-image-role="trigger"
                                   data-image-title="Stayin' Alive"
                                   data-image-url="img/otter1.jpg">
            <img class="thumbnail-image" src="img/otter1.jpg" alt="">
            <span class="thumbnail-title">Barry</span>
          </a>
        </li>
          <li class="thumbnail-item">
            <a href="img/otter2.jpg" data-image-role="trigger"
                                     data-image-title="How Deep Is Your Love"
                                     data-image-url="img/otter2.jpg">
            <img class="thumbnail-image" src="img/otter2.jpg" alt="">
            <span class="thumbnail-title">Robin</span>
          </a>
        </li>
        <li class="thumbnail-item">
          <a href="img/otter3.jpg" data-image-role="trigger"
                                   data-image-title="You Should Be Dancing"
                                   data-image-url="img/otter3.jpg">
            <img class="thumbnail-image" src="img/otter3.jpg" alt="">
            <span class="thumbnail-title">Maurice</span>
          </a>
        </li>
        <li class="thumbnail-item">
          <a href="img/otter4.jpg" data-image-role="trigger"
                                   data-image-title="Night Fever"
                                   data-image-url="img/otter4.jpg">
            <img class="thumbnail-image" src="img/otter4.jpg" alt="">
            <span class="thumbnail-title">Lesley</span>
          </a>
        </li>
        <li class="thumbnail-item">
          <a href="img/otter5.jpg" data-image-role="trigger"
                                   data-image-title="To Love Somebody"
                                   data-image-url="img/otter5.jpg">
            <img class="thumbnail-image" src="img/otter5.jpg" alt="">
            <span class="thumbnail-title">Barbara</span>
          </a>
        </li>
...

Add data attributes for the detail image, as well:

...
      <div class="detail-image-container">
        <div class="detail-image-wrapper">
    <img class="detail-image" data-image-role="target" src="img/otter1.jpg" alt="">
    <span class="detail-image-title" data-image-role="title">Stayin' Alive</span>
        </div>
      </div>
...

Your JavaScript code can refer to these data attributes to access specific elements on the page because the browser lets you use JavaScript to make queries about the contents of a web page. For example, you can query for any elements that match a selector, such as data-image-role="trigger". If the query finds matches, it will return references to the matching elements.

When you have a reference to an element, you can do all sorts of things with the element. You can read or change the values of its attributes, change the text inside of it, and even get access to the elements around it. When you make changes to an element using a reference, the browser updates the page immediately.

In this chapter, you will write JavaScript code that will get references to the anchor and detail image elements, read the values from the anchor’s data attributes, and then change the value of the detail image’s src attribute. This is how you will make Ottergram interactive.

You may have noticed that the anchor tags and the detail image’s <img> tag all have a data-image-role attribute, but their values are different.

Using the same data attribute names for the anchor and <img> tags is not required, but it is a good practice. It reminds you, the developer, that these elements will be part of the same JavaScript behavior.

One last change is needed in your HTML before you begin work on your JavaScript: You need to tell the HTML to run the JavaScript. Do this by adding a <script> tag in index.html. This <script> tag will refer to the file scripts/main.js, which you will create in just a moment.

...
        </div>
      </div>
    </main>
    <script src="scripts/main.js" charset="utf-8"></script>
  </body>
</html>

When the browser sees a <script> tag, it begins running the code in the referenced file immediately. JavaScript cannot access an element within your HTML before it has been rendered by the browser, so putting the <script> tag at the bottom of the body ensures that your JavaScript does not run until after all the markup has been parsed.

Your HTML is now ready to connect with the JavaScript you are about to write. Be sure to save index.html before you move on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.116.51