9.7.4 Leash: A Complete Guide to the CodeHS Exercise
The 9.7.4 leash exercise is a beginner-friendly JavaScript graphics activity that helps students understand how interactive objects respond to mouse movement. The task combines a circle, a line, and screen coordinates to create a simple visual effect in which a moving object stays connected to a fixed point. Although the program may look small, it introduces several important programming concepts, including event handling, graphical objects, functions, and coordinate-based positioning. Understanding these ideas makes the exercise easier to complete and gives students a useful foundation for building animations, games, and interactive applications.
For students working through an introductory computer science course, the main challenge is not drawing a circle or creating a line. It is making both objects respond correctly to the same mouse movement while keeping their positions synchronized. Once the relationship between the mouse coordinates, the circle, and the line endpoint becomes clear, the underlying logic is much easier to understand.
What Is 9.7.4 Leash?
The 9.7.4 leash exercise is associated with the CodeHS JavaScript graphics curriculum, specifically a lesson about drawing lines. It teaches students how to create graphical objects and update their positions in response to user input.
The exercise uses a visual metaphor. Imagine a ball connected to a fixed point by a leash. When the ball moves, the leash changes its angle and length while remaining connected to the ball. In the programming version, the mouse controls the moving object, and the line represents the connection between that object and the fixed point.
The core behavior usually involves three elements:
- A fixed anchor point: The location where one end of the line begins.
- A moving circle: The graphical object that follows the mouse pointer.
- A connecting line: The line whose moving endpoint follows the circle.
When the mouse moves, the program reads its current horizontal and vertical coordinates. It then updates the circle’s position and the line’s endpoint using those coordinates.
This is an example of interactive graphics. Instead of displaying an image that remains unchanged, the program responds to a user’s actions.
The exact implementation can vary between CodeHS course versions, so students should compare any example code with the instructions displayed in their own assignment.
What Does the Number 9.7.4 Mean?
The number identifies the exercise’s location within a particular course structure. It is not a JavaScript version number, a graphics measurement, or a specification for a physical leash.
The numbering can be understood as a course section, a lesson within that section, and an individual exercise. In the curriculum associated with this activity, the exercise appears in the Drawing Lines lesson.
This distinction matters because CodeHS offers different courses and course versions. Similar activities may appear under different numbers depending on the curriculum.
If an online tutorial uses a different exercise number, that does not automatically mean the instructions are wrong. The important question is whether the tutorial matches the actual task, programming language, graphics library, and functions required by the student’s course.
Before using an example, check the assignment title and its instructions. Matching the task itself is more reliable than relying on the number alone.
How the Leash Exercise Works
The simplest way to understand the exercise is to separate the program into its individual responsibilities.
First, the program creates a circle and places it on the graphics canvas. It also creates a line that starts at a fixed location. The line initially ends at the same location, so it may appear to have no visible length.
Next, the program registers a mouse movement handler. This tells the graphics environment which function should run when the pointer moves.
When the user moves the mouse, the handler receives information about the event. The program uses the mouse’s X and Y coordinates to reposition the circle and update the line’s moving endpoint.
The result is a circle that follows the pointer while a line remains attached to it.
Step 1: Establish the Anchor Point
The anchor point is the stationary end of the line. It can be positioned at the center of the canvas or at another location specified by the assignment.
If the canvas has a width and height, its center can be calculated using:
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
The first value represents the horizontal center, while the second represents the vertical center.
For example, if a canvas is 400 pixels wide and 300 pixels high, its center is at coordinate (200, 150).
These values give the program a consistent starting point. The anchor remains unchanged as the mouse moves around the screen.
Step 2: Create the Circle
The circle represents the moving object. In a CodeHS JavaScript Graphics environment, a circle can be created with the Circle constructor.
A simplified example is:
var ball = new Circle(20);
ball.setPosition(centerX, centerY);
add(ball);
Here, 20 is the circle’s radius. The setPosition() method positions the circle, and add() places it on the canvas.
This example illustrates the general idea rather than a complete submission. The exact variable scope and initialization should match the structure required by the assignment.
Step 3: Create the Connecting Line
The line connects the fixed anchor to the moving object. A line is commonly created by specifying the X and Y coordinates of both endpoints.
var leash = new Line(
centerX,
centerY,
centerX,
centerY
);
add(leash);
The first coordinate pair identifies the starting endpoint. The second pair identifies the ending endpoint.
Both endpoints initially share the same coordinates. As a result, the line has zero length until the mouse moves and the program updates the endpoint.
This initial setup helps keep the graphics predictable because the line and circle begin in the same general location.
Step 4: Register the Mouse Movement Handler
Creating graphical objects is only part of the exercise. The program also needs a way to respond to mouse input.
A mouse movement handler tells the environment which function to call when the pointer changes position. In a typical CodeHS JavaScript Graphics exercise, this is done with mouseMoveMethod().
For example:
mouseMoveMethod(handleMouseMove);
The function name is passed without parentheses because the program is registering the function for later execution.
Writing handleMouseMove() instead would attempt to call the function immediately rather than passing its reference as the event handler.
This is an important distinction for beginners learning event-driven programming.
Step 5: Update Both Objects
When the mouse moves, the program needs to update two things:
- The position of the circle.
- The moving endpoint of the line.
Both updates must use the same mouse coordinates. If the circle moves to a new location but the line endpoint remains behind, the two objects will no longer appear connected.
The central principle is simple: the circle’s center and the line’s moving endpoint must share the same coordinates.
That relationship is the key to understanding the entire exercise.
Understanding the Main JavaScript Concepts
The exercise is useful because it brings several basic programming ideas together in one visible result. Instead of learning each concept in isolation, students can see how the concepts depend on one another.
1. X and Y Coordinates
A graphics canvas uses coordinates to describe where objects appear.
The X coordinate controls horizontal position. Increasing X generally moves an object to the right, while decreasing X moves it to the left.
The Y coordinate controls vertical position. In many browser-based graphics systems, increasing Y moves an object downward, while decreasing Y moves it upward.
Consider these example coordinates:
| Coordinate | Position on the canvas |
| (100, 100) | A point near the upper-left area |
| (200, 150) | The center of a 400 by 300 canvas |
| (300, 200) | A point farther right and lower down |
The exact location depends on the canvas dimensions, but the principle stays the same.
In this exercise, the mouse provides the changing coordinates. The program does not need to guess where the pointer is. It receives that information from the mouse event and uses it to position the graphical objects.
2. Graphical Objects
A graphical object is an element displayed on a canvas, such as a circle, line, rectangle, or other supported shape.
The circle and line have different purposes in this activity. The circle represents the moving object, while the line connects that object to the anchor point.
It is important to understand that creating an object and moving an object are separate operations.
Creating a circle establishes the object. Adding it places it on the canvas. Updating its position changes where it appears afterward.
A common beginner mistake is to recreate the circle every time the mouse moves. That approach is usually unnecessary and may produce unwanted behavior or leave the canvas cluttered, depending on how the program is written.
A cleaner approach is to create the objects once and then update their properties.
3. Mouse Events
A mouse event is an action or change involving the mouse, such as moving the pointer or clicking a button.
The leash activity responds to mouse movement. Each time the pointer moves, the registered event handler receives information about the new position.
This is an example of event-driven programming. The program waits for an event and runs the appropriate function when that event occurs.
The same general principle is used in many applications:
- A button responds when a user clicks it.
- A drawing application responds when the pointer moves while drawing.
- A game responds to keyboard input.
- A menu opens when a user selects an item.
- An interactive map responds to dragging or clicking.
Understanding mouse events in a small graphics exercise helps students prepare for these more complex interactions.
4. Functions and Event Handlers
A function is a reusable block of code that performs a task.
In this exercise, one function usually initializes the graphics, while another handles mouse movement. Separating these responsibilities makes the program easier to read and troubleshoot.
The initialization function creates the circle and line, positions them, adds them to the canvas, and registers the mouse handler.
The event handler updates the positions whenever the pointer moves.
This separation also helps avoid a common design problem: mixing object creation with repeated updates. When initialization and interaction are handled separately, each part of the program has a clear purpose.
5. Updating Existing Objects
The exercise demonstrates why a program often needs to change an existing object’s properties rather than create a new object for every interaction.
The circle already exists on the canvas. When the mouse moves, the program changes its position.
The line also exists. Instead of replacing the entire line, the program changes its endpoint.
This approach is useful because it maintains a consistent relationship between the graphical objects. It also makes the code shorter and easier to maintain.
A Step-by-Step Approach to Solving the Exercise
Students often find the task easier when they plan the logic before writing code. A structured approach reduces the chance of missing a required object or event handler.
Step 1: Read the Assignment Instructions
Start by identifying what the program must display and how it must behave.
Check the following details:
- Which graphical objects are required?
- Where should the fixed endpoint be located?
- What should follow the mouse?
- Which part of the line should move?
- Which event handler does the course expect?
- Are there specific requirements for color, size, or starting position?
Do not assume every version of the activity uses identical instructions. The assignment in your own course should be the main reference.
Step 2: Identify the Fixed and Moving Coordinates
Write down which coordinates will remain constant and which will change.
For a center-based design, the anchor might use:
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
These coordinates remain fixed after initialization.
The mouse coordinates, by contrast, change whenever the user moves the pointer. The event handler reads those values and uses them to update the circle and line.
Thinking about the coordinates this way prevents accidental movement of the anchor point.
Step 3: Create the Graphics Before Handling Events
Create the circle and line during initialization. Give them their starting positions and add them to the canvas.
This ensures that the objects exist before the event handler attempts to update them.
If an event handler refers to an object that has not been created, the program may produce an error. Similarly, if the objects are declared inside a function but need to be accessed by another function, their scope may prevent the handler from finding them.
The solution is to choose a variable scope that allows both initialization and the event handler to access the same objects.
Step 4: Register the Event Handler
After creating the objects, register the function that responds to mouse movement.
For example, the general pattern is:
mouseMoveMethod(handleMouseMove);
Make sure the function name matches the actual function declaration. A misspelled name or a missing function can prevent the program from responding.
Step 5: Use the Same Mouse Coordinates
Inside the event handler, read the mouse’s current X and Y positions.
Use those values to position the circle and update the line endpoint. Both objects should respond to the same event using the same coordinates.
The logic can be represented as follows:
Mouse moves
The event supplies the current X and Y coordinates.
Read the mouse position
Obtain the horizontal and vertical values.
Move the circle
Set its position to the mouse coordinates.
Update the line
Set its moving endpoint to the same coordinates.
The two updates create the connected movement that gives the activity its name.
Step 6: Test Different Mouse Movements
Do not test the program only by moving the pointer a short distance.
Move it toward each corner, across the center, and along the edges of the canvas. Watch whether the circle follows correctly and whether the line remains attached.
Testing different positions can reveal errors that are not obvious when the mouse moves only a few pixels.
Step 7: Compare the Result With the Requirements
Finally, check the completed program against the original assignment.
Confirm that the line begins at the required anchor, the circle follows the pointer, and the endpoint moves correctly. Also check that the program uses the expected graphics functions and does not generate unnecessary objects.
A program that runs without errors is not automatically correct. Its behavior must also match the exercise requirements.
A Conceptual Code Example
The following example illustrates the main structure of the program. It is intended to explain the logic, so students should verify the required names, object sizes, and initialization details against their own CodeHS assignment.
var ball;
var leash;
function start() {
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
ball = new Circle(20);
ball.setPosition(centerX, centerY);
add(ball);
leash = new Line(
centerX,
centerY,
centerX,
centerY
);
add(leash);
mouseMoveMethod(handleMouseMove);
}
function handleMouseMove(e) {
var mouseX = e.getX();
var mouseY = e.getY();
ball.setPosition(mouseX, mouseY);
leash.setEndpoint(mouseX, mouseY);
}
This example uses common CodeHS JavaScript Graphics conventions. If your course uses different APIs or requires a different structure, follow those instructions instead.
Understanding the Initialization Function
The start() function establishes the initial state of the program.
It calculates the center of the canvas, creates the circle, places it at the center, and adds it to the graphics area. It then creates the line and adds that object as well.
Finally, it registers the mouse movement handler.
The order is important. The circle and line should exist before the handler tries to change them.
Understanding the Event Parameter
The handleMouseMove(e) function accepts an event parameter named e.
In this type of graphics environment, the event object provides information about the mouse movement. The methods e.getX() and e.getY() are used in the example to obtain the current pointer coordinates.
The program stores those coordinates in mouseX and mouseY. This makes the code easier to read because the same values are used in both updates.
Why Both Objects Use the Same Coordinates
The circle is positioned using the current mouse coordinates. The line’s endpoint is then moved to those same coordinates.
If both operations succeed, the circle remains at the end of the line.
Suppose the mouse is at (250, 120). The circle moves to that position, and the line endpoint also moves to (250, 120). The anchor remains unchanged, so the line connects the anchor to the circle.
If the circle used (250, 120) but the line endpoint used (230, 120), the line would stop short of the circle’s center. That would break the intended relationship.
This is why sharing coordinate values is more than a coding convenience. It is the central requirement of the visual behavior.
Common Problems and How to Fix Them
Debugging is an important part of learning to program. If the result does not look right, inspect one behavior at a time rather than rewriting the entire program.
The Circle Does Not Follow the Mouse
This usually points to a problem with event registration, function naming, or the position update.
Check whether the mouse handler is registered correctly. Confirm that the function name in mouseMoveMethod() matches the declared function and that the handler actually calls the circle’s positioning method.
Also verify that the circle is created before the event handler tries to use it.
The Line Does Not Follow the Circle
If the circle moves but the line remains stationary, the event handler may update only the circle.
Check that the line’s endpoint is updated during mouse movement. The endpoint must use the same X and Y values as the circle’s center.
Do not confuse the line’s starting point with its endpoint. Changing the wrong end can make the entire line appear to move in an unexpected way.
The Program Reports an Undefined Variable
A variable may be unavailable because it was declared inside a function and is not accessible where it is needed.
For example, a circle declared with a local variable inside start() may not be available inside a separate event handler. In that case, the handler cannot access the object through that variable.
One common solution is to declare the object variables in a scope shared by both functions and assign the objects during initialization.
This is a lesson about variable scope, not merely a problem with graphics.
The Line Appears to Start in the Wrong Place
Check the coordinates used to create the line.
The first coordinate pair normally represents its starting point, while the second pair represents its endpoint. If the anchor should be at the center, make sure the program calculates the center correctly and does not accidentally use the mouse coordinates for the fixed endpoint.
Remember that the line’s starting point should remain constant throughout the interaction unless the assignment specifies otherwise.
The Program Creates Too Many Circles or Lines
This can happen when the program creates new graphical objects every time the mouse moves.
Mouse movement can trigger many events in a short period. If each event creates another circle or line, the canvas may accumulate objects instead of updating the existing ones.
Create the required objects during initialization, then change their positions inside the event handler.
This is generally more efficient and makes the intended behavior easier to maintain.
The Circle and Line Become Misaligned
If the line stops before reaching the circle, or appears to extend beyond it, compare the coordinates used by the two objects.
Both should be updated using the same mouse position. Also check whether the line is intended to meet the circle’s center or its edge. Those are different geometric positions, and the assignment’s expected appearance determines which one is appropriate.
The Program Works Only After the Mouse Moves
Some implementations initially place the circle and line at the same coordinates, making the line invisible because its length is zero.
The line becomes visible when the pointer moves away from the anchor.
This behavior may be intentional. However, if the assignment expects a visible line immediately, check the required initial positions rather than assuming the event handler is broken.
How to Debug the Exercise Efficiently
A systematic debugging method can save time and make the programming concepts easier to remember.
- Check initialization. Confirm that both graphical objects are created and added to the canvas.
- Check the event registration. Verify that the correct function is registered for mouse movement.
- Check the event data. Make sure the handler reads the current X and Y coordinates correctly.
- Check the circle update. Test whether the circle follows the pointer.
- Check the line update. Confirm that the endpoint uses the same coordinates.
- Check variable scope. Ensure that the event handler can access the objects.
- Check the final behavior. Compare the program with the assignment instructions.
Changing one part at a time makes it easier to identify the source of an error. If you change several things at once, it becomes harder to determine which change solved the problem or introduced a new one.
For additional help with the platform, consult the official CodeHS website. Your course’s own instructions remain the best reference for assignment-specific requirements.
Why This Exercise Matters Beyond the Classroom
The leash activity may appear simple, but it introduces a pattern that appears in many interactive programs: user input changes an object’s state, and the graphics update to reflect that change.
The circle is not moving independently. Its position is determined by the mouse event. The line is also not moving independently. Its endpoint is determined by the same event data.
That relationship is useful in several areas of programming.
Interactive Drawing Applications
A drawing application needs to track the pointer as users create lines, shapes, or freehand marks.
The same principle applies: obtain the pointer coordinates and update the relevant graphical elements. A more advanced drawing tool may also track mouse-button state, brush size, color, and previous pointer positions.
Simple Games
Many games involve objects that follow a cursor, track a character, or remain connected to another object.
A game might use a line to show an aiming direction, a connection between two characters, or the path of a moving object. The leash exercise provides a simple starting point for understanding these relationships.
However, more advanced games may use additional calculations to smooth movement, limit distance, detect collisions, or maintain a particular angle.
Animation and Visual Effects
Animation involves changing graphical properties over time or in response to input.
The leash activity demonstrates movement driven by an event rather than by a continuous timer. That distinction helps students understand different ways to update a visual scene.
Other animations may rely on frame loops, timers, or calculated positions. Learning mouse-driven updates first gives beginners a practical foundation for exploring those techniques.
User Interface Design
Interactive interfaces frequently respond to pointer movement. Hover effects, draggable controls, selection indicators, and movable panels all rely on the relationship between user input and interface state.
The exercise does not teach all of these features directly, but the event-handling pattern is relevant to them.
Benefits of Learning Through the Leash Exercise
There are several reasons this small activity can be useful for new programmers.
Immediate Visual Feedback
Students can see the result of their code as they move the mouse. If an object moves incorrectly, the result provides a direct clue about what may be wrong.
Visual feedback can make abstract ideas such as coordinates and event handlers easier to understand.
Practice With Multiple Objects
The program updates a circle and a line in response to one event. This demonstrates how a single input can influence several objects.
That idea becomes increasingly important as programs become more complex and contain many interacting elements.
Better Understanding of Functions
The activity encourages students to separate initialization from event handling.
Once that structure becomes familiar, students can reuse the same approach in other exercises that respond to clicks, keyboard input, or mouse movement.
Stronger Debugging Skills
The exercise gives beginners a manageable problem with several possible failure points. Students can learn to check variable scope, event registration, object creation, and coordinate updates individually.
These skills are useful throughout programming, regardless of the language or platform.
A Foundation for More Advanced Graphics
Once students understand the basic behavior, they can explore more complex ideas such as movement constraints, distance calculations, object tracking, and animation.
The original exercise does not require those advanced features. Its value lies in establishing a clear foundation before introducing additional complexity.
Challenges Beginners Should Understand
Although the basic idea is straightforward, several concepts may be unfamiliar to students seeing interactive graphics for the first time.
Understanding the Event Lifecycle
In a simple sequential program, instructions often execute from top to bottom. An event-driven program behaves differently.
The initialization function runs first, then the program waits for relevant events. When the mouse moves, the registered handler runs.
Understanding this difference is important because registering a function does not mean it will execute immediately.
Keeping the Objects Accessible
The initialization code and the event handler need access to the same circle and line.
Variable scope determines where a variable can be used. Students who understand this concept can avoid many errors involving undefined variables.
Understanding the Difference Between Position and Endpoint
A circle is positioned by its location, usually its center. A line has two endpoints.
These objects therefore use different methods to represent their geometry. The circle’s position changes, while only the line’s moving endpoint needs to change.
Recognizing this distinction helps students avoid updating the wrong property.
Avoiding Unnecessary Complexity
It can be tempting to add extra variables, functions, or calculations before the basic program works.
A better approach is to solve the required behavior first. Once the circle follows the mouse and the line remains connected, additional features can be considered if the assignment permits them.
Simple code is easier to inspect, explain, and debug.
Practical Ways to Build on What You Learn
After understanding the core behavior, students can experiment with small changes to deepen their understanding.
Change the Circle’s Radius
Adjust the circle’s radius and observe how its appearance changes. This demonstrates the difference between an object’s size and its position.
Keep the assignment’s original requirements in mind if you are modifying a graded exercise.
Change the Anchor Point
Instead of using the center of the canvas, experiment with another fixed coordinate. Observe how the line changes direction as the mouse moves.
This demonstrates that the anchor is simply a coordinate pair, not a special property of the canvas.
Track the Relationship Between Objects
Try explaining the program without looking at the code.
Can you identify which coordinates remain constant? Which coordinates change? Which function reads the mouse position? Which statements update the graphics?
If you can answer these questions clearly, you understand more than the final appearance of the program. You understand the logic that produces it.
Explore Other Input Events
After mastering mouse movement, learn how other event handlers work. A click event could trigger a change in color, while a keyboard event might move an object in a particular direction.
Each interaction has its own event data and registration method, so use the documentation for the relevant environment when exploring these extensions.
The goal is not to add complexity for its own sake. It is to understand how event-driven programs connect user actions to visible results.
Frequently Asked Questions
1. What is 9.7.4 Leash in CodeHS?
It is a JavaScript graphics exercise that teaches students to connect a moving circle to a fixed point using a line. The program responds to mouse movement by updating the circle’s position and the line’s endpoint.
2. Which programming language is used for this exercise?
The exercise discussed here belongs to the JavaScript Graphics portion of the CodeHS curriculum. Students should verify the language and graphics functions in their own course instructions because different courses may organize similar activities differently.
3. How does the circle follow the mouse?
The program registers a mouse movement handler that reads the pointer’s current X and Y coordinates. The handler uses those coordinates to update the circle’s position whenever the mouse moves.
4. Why does the line need an endpoint update?
A line is defined by two endpoints. One endpoint remains at the fixed anchor, while the other follows the moving circle. Updating the endpoint with the circle’s coordinates keeps the two graphical elements connected.
5. Why is my Leash program not working?
Common causes include incorrect event registration, misspelled function names, inaccessible variables, missing graphics objects, and incorrect coordinate updates. Check each part separately, starting with initialization and ending with the mouse movement handler.
6. What programming skills does the exercise teach?
It introduces coordinate systems, graphical objects, functions, mouse events, variable scope, event-driven programming, and updating existing objects. These concepts provide a foundation for interactive graphics, simple games, and other applications.
Conclusion
The 9.7.4 leash exercise is a practical introduction to interactive JavaScript graphics. Its central idea is simple: a circle follows the mouse while a line connects the circle to a fixed point. Achieving this behavior requires students to understand coordinates, create graphical objects, register a mouse event handler, and update the relevant properties when the pointer moves.
The most important lesson is the relationship between user input and graphical state. The circle and line must respond to the same mouse coordinates, while the anchor remains fixed. Creating the objects once and updating them through an event handler keeps the program organized and predictable.
Students who understand the logic behind this activity will be better prepared to work with interactive interfaces, drawing tools, animations, and beginner game projects. Rather than focusing only on whether the final result looks correct, they should understand why each function is needed and how the different parts work together.