The 9.7.4 Leash exercise is a practical introduction to interactive graphics programming in CodeHS. It challenges students to create a ball connected to a line, then make both respond to mouse movement while keeping one end of the line fixed at the center of the graphics canvas.
At first glance, the assignment looks simple. Yet it brings together several essential programming concepts, including JavaScript functions, mouse events, coordinate systems, graphical objects, and event-driven programming.
The real challenge is not drawing a circle or a line independently. It is making two separate graphical objects behave as a connected system without recreating them every time the mouse moves.
This guide explains the assignment’s purpose, provides a working example, breaks down the JavaScript logic, and shows how to identify and fix common errors. It also explores how the same concepts apply to animation, browser-based graphics, interactive applications, and game development.
What Is 9.7.4 Leash in CodeHS?
9.7.4 Leash is a JavaScript graphics exercise included in the Drawing Lines lesson of the CodeHS Introduction to Computer Science in JavaScript curriculum.
The official CodeHS course outline identifies it as Exercise 9.7.4 under Lesson 9.7, immediately after the Drawing Lines example. In the published 2022 Golden and Bulldog course versions, the exercise is worth five points.
The assignment demonstrates how a graphical object can move in response to user input while remaining visually connected to a stationary point.
Instead of producing a static illustration, students build a small interactive program. The mouse determines the ball’s location, and a connecting line updates automatically to follow its movement.
Understanding the Exercise Requirements
In the commonly documented version of 9.7.4 Leash, the program must maintain a clear relationship between the ball, the line, and the mouse pointer.
Its main requirements are:
Create a circle: Represent the movable ball using the JavaScript Graphics
Circleobject.Create a line: Draw a connection between the canvas center and the ball.
Set the initial position: Place the ball and both line endpoints at the center.
Detect mouse movement: Use a mouse-event handler to obtain the pointer’s current coordinates.
Update the ball: Move the circle to the current mouse position.
Update the line: Move only the line’s ending point, preserving its fixed starting position.
An early student discussion includes the assignment instructions describing precisely this behavior: a ball beginning at the canvas center, with a line whose endpoint follows the mouse.
The result resembles an object attached to a flexible leash. As the cursor moves around the screen, the line stretches, rotates, and contracts while maintaining the connection.
Why Is It Called a Leash?
The name describes the visual relationship between the two objects.
Imagine a ball attached to a rope fixed at one end. Moving the ball changes the rope’s direction and visible length, but the rope remains connected to its anchor.
The programming exercise recreates that appearance using coordinates rather than physical movement.
Unlike a realistic rope simulation, however, the basic exercise does not enforce a maximum leash length, gravity, or tension. Its purpose is to demonstrate synchronized graphical updates, not physical simulation.
How 9.7.4 Leash Works: The Basic Programming Logic
The 9.7.4 Leash activity works by establishing a connection between a fixed coordinate and a moving coordinate.
The canvas center remains constant throughout the program. Meanwhile, the mouse pointer supplies new X and Y values whenever the user moves it.
These values control two graphical properties simultaneously: the circle’s center and the line’s endpoint.
Understanding the Coordinate System
In CodeHS graphics, every visible object has a position determined by coordinates.
The X coordinate represents horizontal movement, while the Y coordinate represents vertical movement. Typically, the upper-left corner of the graphics canvas is (0, 0), and Y values increase as you move downward.
For example, consider a canvas measuring 400 pixels wide and 500 pixels high.
| Position | X coordinate | Y coordinate |
|---|---|---|
| Top-left corner | 0 | 0 |
| Canvas center | 200 | 250 |
| Mouse position A | 100 | 150 |
| Mouse position B | 320 | 400 |
The center is calculated by dividing the canvas width and height by two.
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;This calculation is more flexible than hardcoding the center as (200, 250).
If the graphics window changes size, the program still calculates the correct center automatically.
Understanding the Fixed and Moving Points
The 9.7.4 Leash program has three important coordinate relationships:
Fixed anchor: The starting point of the line remains at the canvas center.
Moving endpoint: The line’s ending point follows the mouse.
Ball position: The circle’s center uses the same coordinates as the moving endpoint.
For instance, if the cursor moves to (300, 180), the ball moves to that location. The line changes to connect the canvas center to (300, 180).
This simple relationship creates the entire interactive effect.
Complete 9.7.4 Leash JavaScript Code Example
The following solution demonstrates the standard 9.7.4 Leash graphics behavior using CodeHS JavaScript.
It creates a yellow ball with a 30-pixel radius and a black connecting line. Both objects begin at the canvas center, and the ball follows the mouse while the line stays attached.
The program uses methods documented in the official CodeHS JavaScript Graphics reference, including Circle, Line, setPosition(), setEndpoint(), and mouseMoveMethod().
var BALL_RADIUS = 30;
var ball;
var leashLine;
function start() {
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
// Create the connecting line
leashLine = new Line(
centerX,
centerY,
centerX,
centerY
);
leashLine.setColor(Color.black);
add(leashLine);
// Create the moving ball
ball = new Circle(BALL_RADIUS);
ball.setPosition(centerX, centerY);
ball.setColor(Color.yellow);
add(ball);
// Detect movement of the mouse
mouseMoveMethod(moveLeash);
}
function moveLeash(e) {
var mouseX = e.getX();
var mouseY = e.getY();
// Move the ball
ball.setPosition(mouseX, mouseY);
// Move only the line's endpoint
leashLine.setEndpoint(mouseX, mouseY);
}Important: This is an independently written illustrative implementation, not a claimed official CodeHS answer key. Some classroom versions may specify different names, colors, object sizes, or starter code, so students should follow their assigned instructions.
What Happens When You Run the Program?
When the program starts, a yellow ball appears in the center of the canvas. The line initially has zero length because its two endpoints occupy the same position.
As soon as the mouse moves, the ball follows the pointer and the line stretches toward its new location.
The black line remains connected to the circle, while its opposite end stays anchored at the original center.
The same behavior continues as the cursor moves toward different corners or returns to the center.
Step-by-Step Explanation of the 9.7.4 Leash Code
Understanding each part of the code is more valuable than memorizing the complete example.
The exercise becomes easier when it is divided into object creation, coordinate calculation, mouse-event registration, and graphical updates.
Step 1: Declare the Variables
The program begins by defining the objects that will be needed throughout its execution.
var BALL_RADIUS = 30;
var ball;
var leashLine;BALL_RADIUS stores the ball’s radius in pixels. The other two variables hold references to the graphics objects created later.
These variables are declared outside the functions because both start() and moveLeash() need access to the same circle and line.
Step 2: Calculate the Canvas Center
The next task is finding the center of the graphics screen.
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;getWidth() returns the canvas width, while getHeight() returns its height.
Dividing both values by two gives the horizontal and vertical coordinates of the center.
The 9.7.4 Leash example uses these calculations to avoid depending on one specific canvas size.
Step 3: Create the Line
The line is constructed with four coordinate values.
leashLine = new Line(
centerX,
centerY,
centerX,
centerY
);The first two values identify the starting point. The final two values identify the ending point.
Initially, these points are identical because the leash has not yet extended toward a moving ball.
After construction, add(leashLine) places the object on the graphics canvas.
Step 4: Create and Position the Ball
The circle represents the movable object.
ball = new Circle(BALL_RADIUS);
ball.setPosition(centerX, centerY);
ball.setColor(Color.yellow);
add(ball);The Circle constructor creates a circular graphics object. The setPosition() method places its center at the specified coordinates.
The color-setting method changes the ball’s appearance, and add() displays it.
In this example, the line is added before the ball so the circle appears visually above the connection.
Step 5: Register the Mouse Event
The most important interaction begins with:
mouseMoveMethod(moveLeash);This command tells CodeHS which function should execute when mouse movement occurs.
Notice that moveLeash is written without parentheses. That is intentional.
The function itself is passed as a callback, allowing CodeHS to execute it when the appropriate event occurs. This usage matches the platform’s official mouse-event documentation.
Step 6: Read the Mouse Coordinates
The movement function receives an event parameter named e.
function moveLeash(e) {
var mouseX = e.getX();
var mouseY = e.getY();
}Here, e.getX() returns the current horizontal mouse position, while e.getY() returns the vertical position.
Each movement event supplies updated coordinates.
The 9.7.4 Leash animation depends on reading both coordinates correctly because the ball needs to respond to horizontal and vertical movement.
Step 7: Update Both Objects
The final operation synchronizes the circle and line.
ball.setPosition(mouseX, mouseY);
leashLine.setEndpoint(mouseX, mouseY);Both statements use exactly the same coordinate values.
The circle moves to the new pointer position, while the line’s ending point moves to the circle’s center.
The starting point of the line remains unchanged, preserving the appearance of a fixed anchor.
Understanding setPosition() vs. setEndpoint()
One of the most important lessons in 9.7.4 Leash is knowing when to use setPosition() and when to use setEndpoint().
Although the names seem similar, their purposes are different.
| JavaScript method | Purpose | Effect in the exercise |
|---|---|---|
setPosition(x, y) on a Circle | Moves the circle’s center | Repositions the ball |
setEndpoint(x, y) on a Line | Changes the line’s ending point | Extends or rotates the leash |
setPosition(x, y) on a Line | Changes the line’s starting point | Moves the anchor |
add(object) | Adds an object to the canvas | Makes the object visible |
mouseMoveMethod(functionName) | Registers a movement callback | Activates mouse tracking |
The official CodeHS Line documentation distinguishes a line’s starting point from its endpoint, confirming why the two methods are not interchangeable.
For the standard implementation, setEndpoint() should update the moving end of the line.
Changing the line’s starting position instead can destroy the intended fixed-anchor behavior.
Common 9.7.4 Leash Errors and How to Fix Them
Even a short graphics exercise can produce confusing results when objects, variables, or events are configured incorrectly.
The most effective debugging strategy is to isolate one behavior at a time rather than rewriting the entire program.
Error 1: The Ball Does Not Move
If the ball appears but remains stationary, the mouse callback may not be registered correctly.
Check that the program contains a valid mouse-event registration:
mouseMoveMethod(moveLeash);Then verify that the corresponding function exists and accepts the event parameter.
A missing or misspelled function name can prevent the expected interaction.
Error 2: The Line Does Not Follow the Ball
This problem usually occurs when the program changes the ball’s position without changing the line’s endpoint.
Check that the movement function updates both objects.
ball.setPosition(mouseX, mouseY);
leashLine.setEndpoint(mouseX, mouseY);The two methods should use matching coordinates.
Error 3: The Line Disappears
A line may be invisible at startup because both endpoints are located at the same position.
That is normal in the basic 9.7.4 Leash example.
Move the mouse away from the center before assuming the program has failed.
If the line remains invisible, confirm that it was added to the canvas and that its endpoint is changing.
Error 4: Undefined Variable Errors
JavaScript is case-sensitive, and variables must be accessible wherever they are used.
For example, ball and Ball are different identifiers.
If the movement function references a variable declared only inside start(), it may not be able to access that object.
Declare shared graphics-object variables outside the functions or otherwise ensure they are in the appropriate scope.
Error 5: Multiple Balls Appear
Another common mistake is creating a new circle every time the mouse moves.
For example, placing new Circle() inside the mouse-event handler can cause unnecessary object creation.
Instead, create the circle once during initialization and update the existing object with setPosition().
This produces cleaner code and avoids accumulating graphical objects.
Error 6: The Entire Line Moves
If the entire line shifts instead of stretching, the wrong update method may be used.
For the standard exercise, keep its starting point fixed and use setEndpoint() to update only the other end.
Avoid calling move() or modifying the starting coordinates unless the assignment specifically requires that behavior.
How to Test 9.7.4 Leash Correctly
Running a program without an error message does not necessarily mean that its behavior is correct.
The best test is to verify each expected visual result systematically.
Use the following checklist for the 9.7.4 Leash implementation:
| Test | Action | Expected result |
|---|---|---|
| Initial display | Run the program | One circle appears at the center |
| Horizontal movement | Move the mouse to the right | Ball follows; line extends right |
| Vertical movement | Move the mouse downward | Ball follows; line extends down |
| Diagonal movement | Move toward a corner | Line rotates and stays attached |
| Return to center | Move the mouse back | Line contracts toward zero length |
| Repeated movement | Move rapidly around the canvas | No additional circles are created |
| Fixed-anchor check | Observe the original center | Starting point remains unchanged |
Testing different directions helps reveal problems that might not be obvious when the cursor moves along only one axis.
For example, a program that accidentally exchanges X and Y coordinates may behave strangely during diagonal movement.
An Important Coordinate Check
Suppose a 400-by-500-pixel canvas has a fixed center at (200, 250).
If the mouse moves to (350, 100), the expected positions are:
Line starting point:
(200, 250)Line ending point:
(350, 100)Circle center:
(350, 100)
The circle center and line endpoint should always match.
This simple mathematical comparison is one of the quickest ways to identify coordinate-related errors.
Why 9.7.4 Leash Is Important for Learning JavaScript
The 9.7.4 Leash assignment teaches more than basic line drawing.
It introduces the structure of event-driven programming, where code executes in response to an action rather than simply running sequentially from beginning to end.
The application first creates its objects and registers the callback. After that, user interaction triggers the updates.
This model appears throughout modern interactive software.
Event-Driven Programming
A mouse event represents information about something the user has done.
The program does not have to manually guess when the pointer changes position. Instead, the event system invokes a registered function when movement occurs.
The same principle applies to button clicks, keyboard input, dragging, and other interactions.
Managing Shared Application State
The ball and line are independent graphics objects, but they must respond consistently to the same input.
Both therefore rely on shared coordinate values.
Understanding how to coordinate multiple objects is useful when developing more complicated interfaces, simulations, and games.
Separating Initialization From Updates
A well-organized program distinguishes between creating objects and changing their existing properties.
In this exercise, start() performs initialization, while moveLeash() handles movement.
This separation improves readability, supports debugging, and reduces unnecessary object creation.
9.7.4 Leash vs. 4.7.4 Leash: Are They the Same?
Students sometimes discover tutorials using different exercise numbers for an activity with the same name.
That does not necessarily indicate that the tutorial is incorrect.
CodeHS organizes its activities differently across courses and curriculum editions.
For example, the official Introduction to Computer Science in JavaScript (2022) outline lists Leash as Exercise 9.7.4. Another official CodeHS Foundations curriculum lists a Leash exercise as 16.2.4, while other course structures use different section numbers.
The exercise number identifies its position within a particular course structure, not the version of JavaScript.
Before applying code from another tutorial, compare the assignment description, required objects, initial coordinates, and expected interaction.
A program demonstrating similar visual behavior may still fail an assessment if the assigned requirements differ.
How to Improve the 9.7.4 Leash Program
Once the basic implementation works, several small improvements can strengthen your understanding of interactive graphics.
These enhancements are optional practice ideas rather than requirements of the original assignment.
Customize the Appearance
Experiment with the color and dimensions of the objects.
For example:
ball.setColor(Color.red);
leashLine.setColor(Color.blue);
leashLine.setLineWidth(4);These changes allow students to see how graphics properties can be modified independently of object positions.
Keep the required colors and sizes unchanged when submitting an assignment with specific visual criteria.
Experiment With Mouse Events
The basic exercise uses mouseMoveMethod() because the ball should respond whenever the pointer moves.
An alternative experiment is to try mouseDragMethod() and compare the behavior.
With a drag handler, movement is associated with dragging rather than ordinary pointer movement.
This comparison helps explain why event selection matters when designing interactive applications.
Explore a Maximum Leash Length
A more advanced extension is to limit how far the ball can travel from its anchor.
That requires calculating the distance between two points:
The application can compare that distance with a predefined maximum length.
If the distance exceeds the limit, the program could restrict the ball’s position to the boundary of the permitted range.
This extension introduces coordinate geometry, distance calculations, vector normalization, and conditional logic.
It should not be confused with the basic assignment, which only requires synchronized movement of a circle and line.
Practical Applications Beyond the Classroom
The concepts introduced by 9.7.4 Leash appear in numerous real-world software applications.
Interactive graphics systems regularly need to track a moving pointer while keeping visual elements connected.
Examples include diagramming tools, draggable interface elements, educational games, interactive maps, and visual editing applications.
Consider a diagram editor where an arrow connects two boxes.
When a user drags one box, the arrow must update to follow its new position without becoming detached from the other box.
This resembles the same coordinate relationship used in the Leash exercise.
Likewise, drawing applications track mouse events to create strokes, while graphical games use position updates to move objects or display connections.
The underlying lesson is transferable: multiple graphical elements can respond coherently when they share a consistent representation of position.
Frequently Asked Questions About 9.7.4 Leash
1. What is 9.7.4 Leash in CodeHS?
It is a JavaScript graphics exercise in the Drawing Lines section of the CodeHS Introduction to Computer Science curriculum.
The commonly documented task involves creating a ball connected to a line, placing both at the canvas center, and updating the ball and the line’s endpoint whenever the mouse moves.
Its primary learning objectives are understanding coordinates, mouse-event callbacks, graphics methods, and object positioning. It is a beginner-friendly introduction to event-driven graphical programming.
2. How do you make the ball follow the mouse?
Register a mouse-movement callback using mouseMoveMethod().
Inside the callback, retrieve the cursor coordinates using e.getX() and e.getY(), then pass those values to the circle’s setPosition() method.
To preserve the leash connection, update the line’s endpoint using the same coordinate pair. Creating both objects once and changing their positions afterward is the simplest approach.
3. Why is my 9.7.4 Leash CodeHS answer not working?
The most common causes include incorrect variable scope, missing mouse-event registration, misspelled method names, and failure to update the line endpoint.
First, confirm that both graphics objects are created and added to the canvas. Then check that the callback is registered and uses valid mouse coordinates.
If the program runs but the line appears missing, move the cursor away from the canvas center. A zero-length line can be invisible even when the code is behaving correctly.
4. What does setEndpoint() do in CodeHS?
The setEndpoint(x, y) method changes the ending point of an existing Line object.
It allows the line to change its length and direction while preserving the starting point, provided that no other code modifies the start.
In the Leash exercise, this method keeps the connection aligned with the ball’s changing position. It is different from moving the entire line or replacing it with a new object.
5. Is the 9.7.4 Leash exercise difficult for beginners?
The assignment is manageable for beginners familiar with JavaScript functions, variables, and the basics of CodeHS graphics.
The most challenging concept is usually understanding how a mouse event supplies coordinates to a callback function.
Once students recognize that the circle center and line endpoint must share the same coordinates, the logic becomes straightforward. Practice with simple mouse-controlled circles and lines can make the exercise significantly easier.
Conclusion: Master 9.7.4 Leash by Understanding the Logic
The 9.7.4 Leash exercise is a small but valuable programming challenge that connects several essential JavaScript concepts.
Its central idea is straightforward: create a circle and line, anchor one end of the line at the canvas center, and update the circle and line endpoint using the same mouse coordinates.
Successfully implementing that behavior demonstrates an understanding of graphical objects, coordinate systems, callbacks, variable scope, and interactive updates.
To get the most from this exercise, run the example, move the mouse in every direction, inspect the results, and experiment with one change at a time.
After the basic program works, try changing the colors, exploring different mouse events, or adding a maximum leash length as a separate challenge.
The goal is not merely to produce code that passes a test. It is to understand the underlying relationship between user input and graphical behavior, so you can apply the same principles confidently to more advanced JavaScript projects.




