Home > Articles

  • Print
  • + Share This
This chapter is from the book

Changing Images Based on User Interaction

Chapter 4 introduced you to the concept of user interaction events and their event handlers, such as the onclick event handler when a click action is made by the user. In that chapter, you invoked changes in a window display based on user interaction; in this section, you’ll see an example of a visible type of interaction that is both practical and dynamic.

Figure 6.11 shows a page that contains one large image with some text next to it, and three small images farther down the page. If you look closely at the list of small images, you might notice that the first small image is, in fact, a smaller version of the large image that is displayed. This is a common display type for a small gallery, such as one you might see in an online catalog where an item has a description and a few alternate views of the product. Although close-up images of the details of products are important to the potential buyer, using several large images on a page becomes unwieldy from both a display and bandwidth point of view, so this type of gallery view is a popular way to display alternative images. I don’t personally have products to sell, but I do have pictures of big trees that I can use as an example, as you can see in the figure.


FIGURE 6.11 An informational page with a main image and alternative images ready to click and view.

The large image on the page is called using the following <img> tag:

   style="border: 1px solid black; margin-right: 13px;"
   alt="large photo">

The style, src, and alt attributes should all make sense to you at this stage of the game. Additionally, as you can see, this image is given an ID of large_photo. Therefore, this image exists in the DOM as document.images['large_photo']—images are referred to by their ID. This is important because a bit of JavaScript functionality enables us to dynamically change the value of document.images['large_image'].src, which is the source (src) of the image.

The following code snippet creates the third small image in the group of three images shown at the bottom of Figure 6.11. The onclick event indicates that when the user clicks on this small image, the value of document.images['large_image'].src—the large image slot—is filled with the path to a matching large image.

<a href="#"
  onclick="document.images['large_photo'].src =
  style="border: 1px solid black; margin-right: 3px;"
  alt="photo #1"></a>

Figure 6.12 shows the same page, but not reloaded by the user. The slot for the large image is filled by a different image when the user clicks one of the other smaller images at the bottom of the page.


FIGURE 6.12 The large image is replaced when the user clicks a smaller image.

  • + Share This
  • 🔖 Save To Your Account