9.7.4 Leash: Complete CodeHS Guide, JavaScript Solution, and Step-by-Step Explanation
The 9.7.4 Leash exercise is a beginner-friendly programming activity that introduces students to interactive graphics, mouse movement, coordinates, and event-driven programming. It is commonly associated with the Drawing Lines section of CodeHS JavaScript Graphics. The main challenge is to create a graphical object that follows the mouse pointer while a line connects it to a fixed point on the screen.
At first, the assignment may seem difficult because it combines several programming concepts in a single task. However, once you understand how graphical objects, variables, and mouse events work together, the solution becomes much easier to build and troubleshoot.
This guide explains what 9.7.4 Leash means, how the program works, which JavaScript graphics methods are important, and how to identify common coding mistakes. It also includes an example solution, practical debugging techniques, and answers to frequently asked questions.
Whether you are studying computer science in the United States, India, or another country, understanding the logic behind this exercise can help you develop programming skills that apply to many other interactive projects.
What Is 9.7.4 Leash?
9.7.4 Leash is a programming exercise that demonstrates how to create an interactive graphic using JavaScript. It focuses on drawing a line, creating a movable object, and updating both elements when the mouse moves across a graphics canvas.
The word leash describes the visual effect created by the program. Imagine a ball attached to a fixed point by a thin string. When the ball moves, the string stretches or changes direction while remaining connected to the same anchor point.
The program recreates this behavior on a computer screen. A circle represents the moving ball, while a line represents the leash. One endpoint of the line stays in a fixed location, and the other endpoint follows the mouse pointer.
The exercise helps students understand several important programming concepts:
- Creating and displaying graphical objects.
- Using variables to store references to objects.
- Calculating the center of a graphics canvas.
- Reading the current mouse coordinates.
- Registering an event handler.
- Updating an existing object’s position.
- Keeping multiple graphical elements synchronized.
These concepts are useful beyond a single classroom assignment. They also appear in drawing applications, browser games, interactive demonstrations, and other software that responds to user input.
What Does the Number 9.7.4 Mean?
The number 9.7.4 identifies the position of an exercise within a particular course structure. In a course organized into numbered units and lessons, the number can indicate a section, a lesson, and an individual activity.
For the commonly referenced CodeHS JavaScript Graphics exercise, Leash is associated with Lesson 9.7, Drawing Lines. However, numbering can differ between courses, curriculum versions, and educational programs.
This distinction matters because a student may encounter a similar exercise under another number. The title, instructions, expected behavior, and available programming methods are more useful for identifying the correct task than the number alone.
If your assignment is labeled 9.7.4 Leash, begin by reading the instructions provided in your own course. Check the required ball size, initial position, line color, and expected mouse behavior. These details determine whether an example solution needs adjustment.
The general programming principle remains the same: create the graphical elements, establish their initial positions, and update the appropriate coordinates when a mouse movement occurs.
What Is the Main Goal of the Leash Assignment?
The primary goal is to build a small interactive program rather than a static drawing.
A static graphic displays objects in fixed positions. Once the program creates the objects, they remain where they were placed unless the code changes their properties.
An interactive graphic behaves differently. It responds to actions performed by the user. In the Leash exercise, mouse movement provides the input that changes the displayed picture.
The intended behavior can be divided into three parts.
First, create the ball and line. The program places a circle near the center of the canvas and draws a line beginning at the same point.
Second, detect mouse movement. A registered mouse event handler allows the program to receive updated coordinates whenever the pointer moves.
Third, update both graphical elements. The circle moves to the current mouse position, and the line’s moving endpoint changes to the same coordinates.
When these steps work together, the line appears to connect the ball to its original anchor point.
The assignment is therefore not simply about drawing a circle or creating a line. It is about making existing graphical objects respond to an event while preserving their relationship to each other.
Understanding the JavaScript Graphics Canvas
Before writing the solution, it helps to understand the canvas.
A graphics canvas is the area where a program displays shapes, lines, and other visual elements. In a CodeHS graphics environment, the canvas has a width and a height that can be accessed through functions such as getWidth() and getHeight().
The canvas uses a coordinate system to determine where each object appears.
The horizontal coordinate is called the X coordinate. It describes a position from left to right.
The vertical coordinate is called the Y coordinate. It describes a position from top to bottom.
In the standard screen coordinate system, the origin is generally located in the upper-left corner. Moving right increases the X coordinate, while moving down increases the Y coordinate.
For example, a point with coordinates (100, 80) is positioned 100 units from the left edge and 80 units from the top edge.
The center can be calculated by dividing the canvas width and height by two:
centerX = getWidth() / 2
centerY = getHeight() / 2
These calculations allow the program to find the center without assuming that every screen has identical dimensions.
Using the canvas dimensions is more flexible than entering fixed coordinates manually. If the available drawing area changes, the center calculations can still position the initial objects correctly.
Complete Example Solution for 9.7.4 Leash
The following example demonstrates the main logic of the Leash exercise in a CodeHS-style JavaScript Graphics environment. Check the instructions in your course before submitting it, particularly if your assignment specifies different dimensions, colors, or variable names.
var BALL_RADIUS = 30;
var ball;
var line;
function start() {
    var centerX = getWidth() / 2;
    var centerY = getHeight() / 2;
    line = new Line(
        centerX,
        centerY,
        centerX,
        centerY
    );
    line.setColor(Color.black);
    add(line);
    ball = new Circle(BALL_RADIUS);
    ball.setPosition(centerX, centerY);
    ball.setColor(Color.yellow);
    add(ball);
    mouseMoveMethod(leash);
}
function leash(e) {
    ball.setPosition(e.getX(), e.getY());
    line.setEndpoint(e.getX(), e.getY());
}
This example creates the ball and line once, then changes their positions in response to mouse movement. It illustrates the standard approach to this type of interactive graphics exercise.
If your teacher has supplied a starter program, preserve any required code and adapt the relevant sections instead of replacing everything automatically.
Step-by-Step Explanation of the Code
Understanding the purpose of each statement is more valuable than memorizing a complete solution. The following sections explain how the example works.
Step 1: Define the Ball Radius
The first statement is:
var BALL_RADIUS = 30;
This creates a variable that stores the circle’s radius. The radius determines the distance from the center of the circle to its edge.
A radius of 30 creates a circle with a diameter of 60 graphics units.
Using a named constant makes the code easier to maintain. If the assignment requires a different radius, you can change the value in one place rather than searching through several statements.
The example uses 30 as an illustration. Always use the value required by your assignment when a specific size is provided.
Step 2: Declare the Shared Variables
The next statements are:
var ball;
var line;
These variables store references to the two graphical objects. They are declared outside the functions so that both start() and leash(e) can access them.
This is important because the program creates the objects in one function and updates them in another.
If the variables were declared only inside start(), the event handler might not be able to access those local variables. This can lead to errors when the program attempts to move the circle or update the line.
Keeping the references in an accessible scope allows the event handler to modify the same objects that were originally created.
Step 3: Calculate the Center of the Canvas
Inside start(), the program calculates the center:
var centerX = getWidth() / 2;
var centerY = getHeight() / 2;
The first statement finds the horizontal center, and the second finds the vertical center.
These values are used to position the initial circle and establish the line’s fixed starting point.
Calculating the center dynamically is generally better than assuming the canvas always has a particular width or height.
Step 4: Create the Line
The line is created with the following constructor:
line = new Line(centerX, centerY, centerX, centerY);
A line constructor receives four coordinate values:
- The starting X coordinate.
- The starting Y coordinate.
- The ending X coordinate.
- The ending Y coordinate.
In this example, both endpoints initially use the center coordinates. As a result, the line begins with zero length.
The program then sets the line color and adds it to the canvas.
line.setColor(Color.black);
add(line);
Adding an object is necessary because creating it in JavaScript does not automatically mean it will appear in the drawing area.
Step 5: Create the Ball
The next section creates the circle:
ball = new Circle(BALL_RADIUS);
The circle is then positioned at the center:
ball.setPosition(centerX, centerY);
Its color is set, and it is added to the canvas.
ball.setColor(Color.yellow);
add(ball);
The ball and the line now begin at the same central location. This provides a clear starting point for the interactive movement.
The order in which graphical objects are added can affect which object appears in front when they overlap. If the assignment requires a particular visual arrangement, follow its directions.
Step 6: Register the Mouse Event Handler
The statement that connects the program to mouse movement is:
mouseMoveMethod(leash);
This tells the graphics environment to call the leash function when the mouse moves over the relevant drawing area.
Notice that the function name appears without parentheses.
The program passes the function as a callback rather than executing it immediately. The graphics environment can then invoke it when the appropriate event occurs.
Without this event registration, creating the circle and line would not be enough to make them respond to mouse movement.
Step 7: Update the Ball and Line
The event handler contains two important statements:
ball.setPosition(e.getX(), e.getY());
line.setEndpoint(e.getX(), e.getY());
The event parameter, named e, provides access to information about the mouse movement.
e.getX() retrieves the mouse’s horizontal coordinate, while e.getY() retrieves its vertical coordinate.
The first statement moves the circle to the current mouse position. The second changes the line’s ending point to those same coordinates.
Because both operations use the same X and Y values, the circle remains connected to the line’s moving endpoint.
This relationship is the central idea behind the entire exercise.
Why Global Variables Matter in the Leash Program
Variable scope determines where a variable can be accessed.
A global or outer-scope variable can be used by multiple functions, depending on where it is declared. A local variable is limited to the function or block in which it is declared.
In the Leash example, the variables ball and line must remain accessible to the event handler after the start() function has finished its initial setup.
Consider the difference between these statements:
ball = new Circle(BALL_RADIUS);
and:
var ball = new Circle(BALL_RADIUS);
When a shared variable has already been declared outside start(), assigning the new circle to that variable preserves the reference needed by the callback. Declaring another variable with the same name inside the function can create a separate local binding.
If the callback tries to use an uninitialized outer variable, the program may fail when mouse movement occurs.
The same principle applies to the line. The event handler needs access to the original line object so it can update its endpoint.
A useful rule is to create each graphical object once, keep a reference to it, and update that object whenever the program responds to an event.
Read more: Allysplay.com: What It Is, Features, Gaming Guides, Safety, and Everything You Should Know
How Mouse Events Work in JavaScript Graphics
A mouse event is an occurrence that a program can respond to, such as moving the pointer, clicking a button, or pressing a mouse button.
Event-driven programming organizes a program around these occurrences. Instead of continuously checking for user input in a manual loop, the program registers a handler that runs when an event happens.
In the Leash exercise, the mouse movement event provides new coordinate information.
The general sequence is straightforward:
- The program initializes the graphics.
- It registers a mouse movement handler.
- The user moves the mouse.
- The graphics environment invokes the handler.
- The handler reads the mouse coordinates.
- The ball and line are updated.
This sequence may repeat many times while the user moves the pointer.
The result is a graphic that appears to follow the mouse continuously. The program does not need to create a new ball for every movement because it can reposition the existing circle.
Event-driven programming is a foundational concept in interactive software. Understanding it makes later assignments involving mouse clicks, keyboard input, and object dragging easier to approach.
Common Errors in 9.7.4 Leash and How to Fix Them
Small programming mistakes can prevent the exercise from behaving correctly. If your solution does not work, check the following issues before rewriting the entire program.
The Ball Does Not Move
If the circle appears on the canvas but remains in the center, first check whether the mouse handler has been registered.
The relevant statement is:
mouseMoveMethod(leash);
Also confirm that the event handler uses the mouse coordinates to update the circle’s position.
ball.setPosition(e.getX(), e.getY());
If the handler is never registered, the program will not respond to mouse movement as expected.
The Line Does Not Follow the Ball
If the circle moves but the line stays in place, inspect the line update statement.
line.setEndpoint(e.getX(), e.getY());
The endpoint must be updated using the same coordinates as the ball.
Check that the variable line refers to the original line object created during initialization. An incorrectly scoped variable or an accidental reassignment can prevent the intended object from being updated.
The Program Reports an Undefined Variable
This problem often occurs when ball or line is declared inside a function and is therefore unavailable to the event handler.
Review the variable declarations at the top of the program. Make sure the callback can access the same objects that start() creates.
Also check spelling and capitalization. JavaScript treats identifiers such as ball, Ball, and BALL as different names.
The Callback Does Not Work
A common mistake is writing the following:
mouseMoveMethod(leash());
This calls the function immediately instead of passing its reference as the event handler.
The intended pattern is:
mouseMoveMethod(leash);
The graphics environment can then call the function when a mouse movement occurs.
The Circle Appears but the Line Is Missing
Check whether the line was added to the canvas using add(line).
Confirm that its constructor receives four coordinate values and that the coordinates are valid numbers.
A line whose starting and ending coordinates are identical has zero length, so it may not be visible initially. In this exercise, that can be expected because the endpoint changes after mouse movement.
The Program Creates Too Many Objects
Do not create a new circle or line every time the mouse moves unless the assignment specifically asks you to draw a trail.
Mouse movement can generate many events in a short period. Creating new objects in every callback can leave old objects behind and make the canvas cluttered.
Create the objects during initialization and update their properties in the event handler instead.
The Objects Move to the Wrong Location
Check that the circle and line endpoint use the same mouse coordinates.
Remember that the X coordinate controls horizontal position and the Y coordinate controls vertical position. Reversing these values can cause unexpected movement.
Also verify that the program uses the correct coordinate methods for the graphics environment.
How to Test Your Leash Program Correctly
Testing should confirm both the initial setup and the response to user input.
Start by running the program. The circle should appear near the center of the canvas, and the line should begin at the same anchor point.
Move the mouse slowly to the right. The circle should follow the pointer, and the line should extend toward it.
Move the mouse to the left, then upward and downward. The ball should continue following the mouse, while the line remains connected to the fixed starting point.
Try moving the pointer diagonally. This checks whether the program handles changes in both X and Y coordinates.
If the behavior is incorrect, test one part at a time. Confirm that the mouse handler runs, then check the circle’s position update, followed by the line endpoint update.
This process is called debugging. Rather than guessing at a solution, you identify which part of the program is not behaving as expected.
If your assignment includes specific requirements for colors, dimensions, or the starting point, verify those details separately. A program can respond correctly to mouse movement and still fail to meet a visual requirement.
What Skills Does the Leash Exercise Teach?
The Leash exercise introduces skills that support more advanced programming tasks.
Coordinate geometry: Students learn how horizontal and vertical coordinates describe positions on a screen.
Object creation: The Circle and Line constructors demonstrate how programs create graphical objects with particular properties.
Variable scope: Shared references allow different functions to access and update the same objects.
Event handling: A registered callback allows the program to respond to mouse movement.
State updates: The circle and line remain in memory while their positions change.
Debugging: Students practice finding problems by checking variables, event registration, and object methods.
These concepts are useful in interactive games, digital drawing tools, visual simulations, and educational applications.
The exercise also introduces an important programming habit: understanding why a solution works instead of relying entirely on copied code.
How the Leash Concept Applies to Games and Other Applications
Although the assignment is small, its underlying idea has many practical applications.
In a simple computer game, a character might follow the mouse pointer. A line could connect a selected object to the cursor to indicate that the object is being dragged.
In a drawing application, a line could stretch from the point where the user started drawing to the current pointer position. Updating the endpoint allows the preview to change as the user moves the mouse.
In a visual editor, a connector could follow a selected node while the user creates a relationship between two objects.
In educational software, moving graphics can demonstrate how coordinate systems and user input work together.
These applications use the same broad principle: an event provides new input, and the program updates the appropriate graphical properties.
More advanced projects may add collision detection, movement constraints, animation timing, or keyboard controls. However, the basic process of storing an object reference and updating its position remains useful.
Best Practices for Writing a Reliable Solution
A clear program is easier to test, understand, and maintain. Several habits can help you write a better solution for this assignment.
Use Descriptive Variable Names
Names such as ball, line, centerX, and centerY make the code easier to read.
For larger projects, descriptive names reduce confusion when multiple graphical objects or coordinate values are involved.
Keep Initialization Separate From Event Handling
Use the initialization function to create the objects and establish their initial positions.
Use the event handler to update the objects in response to user input.
This separation makes it easier to identify whether a problem comes from setup or interaction.
Reuse Existing Objects
Avoid creating duplicate graphics on every mouse movement. Updating an existing object is generally cleaner and more efficient.
Follow the Assignment Requirements
If your course specifies a particular radius, color, position, or function name, use those values. An example solution should support the learning process, not override the instructions of the actual exercise.
Test Small Changes
If you want to experiment, change one property at a time. For example, adjust the circle’s color, run the program, and observe the result.
Testing one change at a time makes cause and effect easier to understand.
Frequently Asked Questions About 9.7.4 Leash
What is 9.7.4 Leash in CodeHS?
It is a JavaScript Graphics exercise commonly associated with a Drawing Lines lesson. The task demonstrates how to make a circle follow mouse movement while a line connects the moving object to a fixed point.
Which programming language is used for the Leash exercise?
The commonly referenced version uses JavaScript with a graphics environment that provides objects and methods such as Circle, Line, setPosition(), and mouseMoveMethod().
The exact requirements should be checked in the course where the exercise appears.
Why does the ball follow the mouse?
The event handler reads the current mouse coordinates through e.getX() and e.getY(). It passes those values to ball.setPosition(), updating the circle’s location.
Why does the line move when the mouse moves?
The program changes the line’s endpoint using the current mouse coordinates. Its starting point remains fixed, so the line stretches or changes direction as the mouse moves.
Why are the ball and line variables declared outside the functions?
The event handler needs access to the same objects that were created during initialization. Declaring their references in an accessible scope allows the callback to update them later.
What does mouseMoveMethod(leash) do?
It registers the leash function as a mouse movement handler. The graphics environment calls the function when the relevant mouse event occurs.
What is the purpose of e.getX() and e.getY()?
These methods retrieve the horizontal and vertical coordinates associated with the mouse event. Together, they identify the pointer’s current position in the graphics canvas.
Why should the circle not be recreated every time the mouse moves?
Repeatedly creating circles can leave multiple objects on the canvas and make the program inefficient. Creating the circle once and changing its position produces the intended tracking effect.
Is 9.7.4 Leash the same in every CodeHS course?
Not necessarily. Similar exercises can appear under different numbers or within different course structures. Always check the instructions and expected behavior in your own assignment.
What should I do if the example does not work in my course?
Compare the example with your starter code and assignment requirements. Check the graphics methods available in your environment, the required variable names, and the expected event handler. Different course versions may require small adjustments.
Can I learn from the exercise without copying the code?
Yes. Start by creating a circle and a line, then calculate their initial positions. Next, register a mouse movement handler and use the event coordinates to update the objects. Testing each part separately helps you understand the program’s behavior.
Final Thoughts on 9.7.4 Leash
The 9.7.4 Leash exercise is a useful introduction to interactive graphics and event-driven programming. It brings together coordinates, graphical objects, variable scope, and mouse events in one manageable task.
The central idea is simple: create the ball and line once, keep their references accessible, and update the circle’s position and the line’s endpoint whenever the mouse moves.
Understanding these steps makes the assignment easier to debug and helps you apply the same principles to future programming projects. Instead of treating the exercise as a collection of commands to memorize, focus on the relationship between the mouse coordinates and the graphical objects.
Once you understand that relationship, the Leash exercise becomes more than a single classroom task. It becomes a practical introduction to how interactive software responds to users, updates visual elements, and turns simple code into a dynamic experience.

One Comment