Lesson 14: Building an App: Image Scroller

Overview

Students will extend the My Favorite Things app they built in the previous lesson so that it now manages and displays a collection of images and responds to key events. Students are introduced to the practice of refactoring code in order to keep programs consistent and remove redundancies when adding new functionality. As part of learning to use key events, students are shown that event handlers pass a parameter which contains additional information about the event. This lesson also serves as further practice at using arrays in programs.

Purpose

Most applications you use are not based on static pieces of code. Instead the software will be continuously updated both to correct errors and introduce new pieces of functionality. If later improvements are anticipated it is generally possible to develop programs in a way that easily incorporates new functionality. At other times it is necessary to make larger changes to the way a program operates in order to incorporate new features while maintaining existing functionality. Refactoring code in this way can be a tedious and challenging endeavor, but it helps ensure that the final product is consistent and easy to maintain. If software is not kept in a logical, consistent, and succinct form, then it will only get harder to keep introducing new features, increasing the likelihood of errors.

Agenda

Getting Started

Activity

Wrap-up

View on Code Studio

Objectives

Students will be able to:

  • Use an array to maintain a collection of data in a program.
  • Create apps that allow user interaction through key events.
  • Refactor code in order to appropriately incorporate new functionality while maintaining readability and consistency.

Vocabulary

  • Key Event - in JavaScript an event triggered by pressing or releasing a key on the keyboard. For example: "keyup" and "keydown" are event types you can specify. Use event.key - from the "event" parameter of the onEvent callback function - to figure out which key was pressed.

Introduced Code

Teaching Guide

Getting Started

Refactoring and re-writing code

Goal

Students should reflect on why adding new functionality to their programs might mean they need to makes changes to the old code they wrote as well.

Thinking Prompt:

  • "When we want to add new functionality to our programs, we'll of course have to write new code. Sometimes, when we add new code to an existing program, we’ll also have to make changes to the original components of our program. Why might this be the case?"

Discuss:

Students may discuss in small groups or you can just ask for ideas from the class. Potential answers include

  • The old code and the new code contradict one another.
  • The old code and the new code may have redundant components.
  • Incorporating the new code may help us find better ways to write the old code.

Transitional Remarks

Writing software is an iterative process. We continuously update and improve our ideas as we learn new techniques, debug our software, or identify new features we’d like to add to our code. While our code will constantly be changing, we’d like it to remain organized, consistent, and readable. As a result, when we add new code to our programs, we may sometimes need to change the way we originally approached a problem.

Today we’re going to be further extending our My Favorite Things app, and seeing how this process plays out in practice.

Activity

App Lab: Building an App - Image Scroller

Wrap-up

Reflection: When to refactor

Goal

Reflect on the process of making improvements to existing code, how to do it well, and how to avoid having to do it too frequently.

Thinking Prompt:

  • "In today’s activity, we needed to make some changes to our programs in order to incorporate new functionality. Sometimes this meant we needed to make changes to our old code as well."

  • Why might you want to change or refactor old code?

  • Is it necessarily a bad thing to refactor code?
  • What steps can we take to avoid refactoring code too frequently?

Discuss:

You can use these questions as an exit ticket, but it is probably even more useful to discuss as a class. Use this discussion to identify and address misconceptions about what refactoring code is and why we would want to do it. Here are some key points to pull out:

  • Refactoring is the process of changing the way we wrote old code in order to keep programs consistent and readable while incorporating new functionality.
  • It is possible that refactoring code will not change the user’s experience but will make the program easier to read and maintain.
  • Refactoring is a useful process, but it can be time consuming and challenging. We’d ideally not refactor code very often but it is sometimes necessary.
  • Good planning and design can help avoid refactoring. Good use of functions and an organized program means that at the very least we limit areas that need to be changed.
  • Lesson Vocabulary & Resources
  • 1
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Notes about this lesson

There are two major things happening in this lesson

  1. Using the event parameter from onEvent to determine which key was pressed.
  2. Modifying the "My Favority Things" Apps made in the last lesson

Helping Students with Incomplete "My Favorite Things" Apps:

It is quite possible that some of your students will not have succeeded in creating the text version of the My Favorite Things app. Since this lesson asks students to extend that project, it might be a challenge for those students to participate. Some strategies are below.

  • Let students continue working on the text version of their app. While this lesson introduces new event types, it falls in a sequence focused on arrays. Students can still participate in discussions about refactoring code and will be exposed to the new key events.

  • Provide students the exemplar version of the text-based My Favorite Things app. They can Remix the project and work on it in Free Play mode (i.e., outside of the curriculum). This way, they have a clean starting point and focus on the content of the lesson. If they wish, students can copy the code into Code Studio and will only need to create the UI elements themselves.

Student Instructions

Unit 5: Lesson 14 - Image Scroller with Key Events

Background

When designing programs, you will often discover new pieces of functionality you wish to add once you have completed a working prototype. Incorporating these new features will of course require writing new code, but it can also often require redesigning the parts of your program you have already written. In this lesson you will extend the "My Favorite Things" app you built in the previous lesson, continuing to practice using arrays in apps while learning how to approach the process of refactoring code.

Vocabulary

  • Key event: an event triggered by pressing or releasing a key on the keyboard.
    • keyup - event type triggered when key is released on the keyboard
    • keydown - event type triggered when key is pressed down on the keyboard
  • event.key - Use event.key - from the event parameter of the onEvent callback function - to figure out which key was pressed.

Lesson

  • Introduction to key events.
  • Improve the "My Favorite Things" app to store and display images.
  • Refactor code in order to incorporate new functionality.

Continue

  • My Favorite Things Demonstration
  • 2
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Making our App an Image Scroller

Over the course of this lesson we are going to be working towards improving our "My Favorite Things" app to add some new features. Our improved app will be able to:

  • Respond to key events.
  • Display images by storing their URLs.

We'll call this new kind of app an image scroller but feel free to call it anything you like.

Do This:

  • Close these instructions.
  • Experiment with the improved "My Favorite Things" app to understand the new features we'll be adding.
  • Make sure you try clicking the left and right arrow keys!

Once you think you've experimented enough, continue on to the next level.

View on Code Studio

Student Instructions

keypress

If we want to add keyboard input to our apps we'll need to learn about how key events work in App Lab. To start let's take a closer look at the onEvent block. We already know that event handlers call a function. What we'll see now is that they also pass a parameter. The default name for this parameter is simply event but you can change it to be anything you like.

The event parameter is a more complex kind of variable (called an "Object") that we'll learn more about later. For now just know that for both mouse and keyboard events, the event parameter passes more information about the event. In the case of key events you can find out the key(s) that were actually pressed by using event.key.

Do This:

  • Drag out an onEvent block.
  • Change the ID to screen1 and the event type to keypress.

  • Once you hit Run, click on the screen so that the keystrokes will register.
  • Type different combinations of keys and check out the results in the console. Does every key combination print to the console? Some keys to try:
    • Letter keys
    • Number keys
    • Shift key
    • Hold shift and letter
    • Delete key
    • Left and right arrow keys
    • Press and hold a key
View on Code Studio

Student Instructions

Using keyup and keydown

On the last level, we played with the keypress event. Let's take a look at some of the other key events.

You are going to get the chance to play with keyup and keydown in this level. Pay attention to the different values of event.key for keydown and keypress.

Do This:

  • Switch to the event type to keydown or keyup.

  • Try out the event.
    • Press and hold a key
    • Try the arrow keys
    • Shift
    • Option
    • Alt
    • Others
View on Code Studio

Student Instructions

Play Sound With Keys

You may have noticed from the last couple of levels that the value of event.key is just a string which is the name of the key. As a result we can check which key was pressed with a simple conditional statement. For example to check for the press of the "a" key we could write if (event.key == "a").

Do This:

The starter code provided plays the sound whenever ANY key is pressed.

  • Use console.log to find out the value of event.key when the up arrow is pressed.

  • Add an if statement so the sound only plays when the when the up arrow is pressed.

View on Code Studio

Student Instructions

Multiple Keys

If you want your program to respond differently to a couple different keys, you will need to use chained conditional statements (if and else-if).

Let's set up the program to play a different sound for the down key.

Do This:

We've added another sound to the app, but it's just sitting at the top of the code.

  • Add an else-if statement to check if the down arrow was pressed.

  • Move the playSound command from the top of the program inside the else-if. (Notice that in the example, we switch to block mode to move this line because it's easier to move blocks around that way. You can just copy/paste the text too.)

  • Test the program: it should play one sound when the up arrow is pressed and a different sound if the down arrow is pressed. It shouldn't make any sound if any other keys are pressed.
View on Code Studio

Student Instructions

Buttons and Keys

We now know how to respond to key events, but often we want the user to be able to do the same thing with the app in multiple ways. For example, we might want the app to exhibit the same behavior if the user clicks a button on the screen or a key on the keyboard. (This is how so-called "keyboard shortcuts" work.)

In the program you're about to see, we've provided event handlers for some buttons on the screen. You're going to create identical functionality for the key events.

Do This:

  • Add conditional statements inside the keydown event handler to check for when the up and down arrows are pressed.

  • Copy the code for the upImage button, and paste into the up arrow if statement.

  • Copy the code for the down button, and paste it into the down arrow if statement.

  • Confirm your app responds to key events by running it. For example, clicking the image of the up arrow in the app should do the same thing as hitting the up arrow on the keyboard.

  • Functions in Your App
  • 8
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Refactoring Code

On the last level, we copied a few lines of code to a different part of our program. Hopefully warning bells went off in your head! Any time you are copying portions of code from one area of your program to another, it's a good indication that you should write a function to capture that behavior in one place.

When you add new features to your code you will often create redundancies. To keep your code readable and consistent, you may need to rewrite old pieces of code. This process of restructuring existing code without changing its external behavior is called refactoring. It is an important process when developing software that improves code readability and reduces complexity. As a result, code is much easier to maintain.

Do This:

  • Create a function called doUpArrow.
  • Move the code from the upArrow event handler to the function.
  • Call doUpArrow from both your button and key event handlers. (The animation below shows the steps above.)
  • Repeat the same process for the down arrow / button by creating a function called doDownArrow.
  • Once you have removed these redundancies from your code test your app to make sure it still works!

  • Adding Images Using URLs
  • 9
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Adding Image URLs

We're ready to start improving the "My Favorite Things" app.

We'll do this in two steps: 1. We will change it from scrolling text to scrolling images. 2. We will add key events to scroll with the keyboard.

Step 1: The default values in your array should be image URLs. The large text area needs to be changed to an image. * Instead of setting the text, you'll now be using setImageURL to set the URL of the image.

Do This:

NOTE: We've re-loaded the code from the "My Favorite Things" App you wrote in the previous lesson. (If you want to refer to code you just wrote, you can go back to look at it.)

  • Set the default values in your array to be image URLs. (You might need to take a minute to go collect a few if you didn't in preparation for this lesson.)
  • In Design Mode delete the text area and replace it with an image. Make sure your image has a descriptive and meaningful ID.
  • Inside your function that updates the display replace setText with setImageURL. Make sure you reference your new image element by its correct ID.
  • Test your app to confirm that it's now showing the images in your array.
  • Project: Image Scroller
  • 10
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Final Image Scroller

You're now ready to add key event functionality to your app! As you are doing so, keep an eye out for places where you need to refactor old code in order to prevent redundancy. Create functions that carry out repeated tasks and make other changes to keep your code readable and consistent.

If you want a reminder of how key events work, you can always go back to the example from earlier in this lesson. You will need to add if statements to check for which keys were pressed, just as before.

Do This:

  • Add the ability to respond to key events to your app.

  • Refactor your old code to remove redundant portions.

  • Keeping adding to your program. What other features do you want to include?

  • My Favorite Things Reflection Question
  • 11
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Free Response: Why Refactor?

Why is refactoring your code important?

Standards Alignment

View full course alignment

Computer Science Principles

5.1 - Programs can be developed for creative expression, to satisfy personal curiosity, to create new knowledge, or to solve problems (to help people, organizations, or society).
5.1.1 - Develop a program for creative expression, to satisfy personal curiosity, or to create new knowledge. [P2]
  • 5.1.1A - Programs are developed and used in a variety of ways by a wide range of people depending on the goals of the programmer.
5.2 - People write programs to execute algorithms.
5.2.1 - Explain how programs implement algorithms. [P3]
  • 5.2.1E - Program execution automates processes.
  • 5.2.1F - Processes use memory, a central processing unit (CPU), and input and output.
  • 5.2.1I - Executable programs increase the scale of problems that can be addressed.
  • 5.2.1J - Simple algorithms can solve a large set of problems when automated.
  • 5.2.1K - Improvements in algorithms, hardware, and software increase the kinds of problems and the size of problems solvable by programming.
5.3 - Programming is facilitated by appropriate abstractions.
5.3.1 - Use abstraction to manage complexity in programs. [P3]
  • 5.3.1A - Procedures are reusable programming abstractions.
  • 5.3.1B - A function is a named grouping of programming instructions.
  • 5.3.1C - Procedures reduce the complexity of writing and maintaining programs.
  • 5.3.1D - Procedures have names and may have parameters and return values.
  • 5.3.1G - Parameters provide different values as input to procedures when they are called in a program.
  • 5.3.1K - Lists and list operations, such as add, remove, and search, are common in many programs.
  • 5.3.1L - Using lists and procedures as abstractions in programming can result in programs that are easier to develop and maintain.
5.4 - Programs are developed, maintained, and used by people for different purposes.
5.4.1 - Evaluate the correctness of a program. [P4]
  • 5.4.1B - Duplicated code can make it harder to reason about a program.
  • 5.4.1C - Meaningful names for variables and procedures help people better understand programs.
  • 5.4.1G - Examples of intended behavior on specific inputs help people understand what a program is supposed to do.
  • 5.4.1M - The functionality of a program is often described by how a user interacts with it.
5.5 - Programming uses mathematical and logical concepts.
5.5.1 - Employ appropriate mathematical and logical concepts in programming. [P1]
  • 5.5.1H - Computational methods may use lists and collections to solve problems.
  • 5.5.1I - Lists and other collections can be treated as abstract data types (ADTs) in developing programs.
  • 5.5.1J - Basic operations on collections include adding elements, removing elements, iterating over all elements, and determining whether an element is in a collection.