CodeHS is a browser-based computer science platform used by middle and high school students across the US. Teachers assign exercises, and students write and run code directly in the browser.
Lesson 9.7 is part of the Animation and Games unit. It builds on what students learned in earlier lessons about shapes, timers, and event handlers. Lesson 9.7.4 specifically is about creating a "leash" — a tether between two objects.
Think of it as the capstone skill for object movement. If you can do this, you can build basic games with followers, companions, or camera tracking.
Imagine a dog on a leash. The dog follows the owner, but only as far as the leash allows. In code, this works the same way.
The follower checks its distance from the leader on every update. If it's too far, it moves closer. That's the whole mechanic.
The CodeHS canvas is a grid. Every object has an X position (left to right) and a Y position (top to bottom). Unlike math class, Y increases downward — not upward.
y - 100 moves an object upward, not downCodeHS lets your program respond every time the mouse moves. This is called event-driven programming. The key method is mouseMoveMethod().
ee.getX() and e.getY()// Example: register the mouse move handler
setMouseMoveMethod(mouseMove);
function mouseMove(e) {
var mouseX = e.getX();
var mouseY = e.getY();
// update object position here
}
Every shape in CodeHS is an object with built-in methods. Two of the most important ones for this exercise are:
| Method | What It Does | Common Mistake |
|---|---|---|
getCenter() | Returns a Point at the center of the shape | Confusing it with getX()/getY() |
setPosition(x, y) | Moves the object to new coordinates | Passing wrong coordinate type |
add(object) | Puts a shape onto the canvas | Forgetting to call it after clearing |
removeAll() | Clears everything from the canvas | Not re-adding objects after clearing |
getCenter() returns a Point object, not a number. To get the X value from it, you call center.x, not just center.
The core math in this exercise is the distance formula. It comes from the Pythagorean theorem and tells you how far apart two points are.
// Distance between two points
var dx = x2 - x1;
var dy = y2 - y1;
var distance = Math.sqrt(dx * dx + dy * dy);
Once you have the distance, you use an if statement: if the distance is greater than your leash length (say, 100 pixels), move the follower toward the leader.
A single position update only moves the object once. For smooth animation, you need the code to run repeatedly.
setTimer(funcName, interval) runs a function every X millisecondsDepending on your specific CodeHS course, this exercise appears in two forms. Read your assignment carefully to know which one you have.
drawLine(), removeAll()Dog class and a Leash classFirst, create a circle. Give it a radius, color, and starting position. Then add it to the canvas.
var ball = new Circle(20);
ball.setColor(Color.red);
ball.setPosition(200, 200);
add(ball);
You need two endpoints for the leash line. In most versions of this exercise, one end is the ball and the other is the mouse cursor.
Most 9.7.4 assignments use a dynamic mouse end and a ball that follows it.
mouseMoveMethod HandlerRegister your mouse move function. Inside it, get the mouse position and move the ball there.
setMouseMoveMethod(mouseMove);
function mouseMove(e) {
var mouseX = e.getX();
var mouseY = e.getY();
ball.setPosition(mouseX - ball.getRadius(), mouseY - ball.getRadius());
}
The - ball.getRadius() offset centers the ball on the cursor instead of placing the corner at the cursor.
Use drawLine() or a Line object to draw the tether. You need the ball's center and the anchor point.
function mouseMove(e) {
var mouseX = e.getX();
var mouseY = e.getY();
removeAll();
// Re-draw ball
ball.setPosition(mouseX - ball.getRadius(), mouseY - ball.getRadius());
add(ball);
// Draw leash line from canvas center to ball center
var center = ball.getCenter();
var line = new Line(200, 200, center.x, center.y);
line.setColor(Color.gray);
add(line);
}
Every time the mouse moves, you need to erase the old drawing and redraw everything. This is done with removeAll().
removeAll() first, before any drawingRun your code and check these things:
Your Dog class needs a constructor with two parameters: name and breed. Store them as instance variables using this.
class Dog {
constructor(name, breed) {
this.name = name;
this.breed = breed;
}
getInfo() {
return this.name + " is a " + this.breed;
}
}
The Leash class holds a reference to a Dog object. This is different from storing a simple string or number — you're storing a full object.
class Leash {
constructor(dog) {
this.dog = dog;
}
getDogInfo() {
return this.dog.getInfo();
}
}
In your main program, create a Dog first. Then pass it into the Leash constructor.
// Main program
var myDog = new Dog("Max", "Labrador");
var myLeash = new Leash(myDog);
// Access dog info through the leash
println(myLeash.getDogInfo());
// Output: Max is a Labrador
Add a println() call to check that the leash correctly returns the dog's info. The data should flow: Leash → Dog → getInfo().
| # | Mistake | What Happens | Fix |
|---|---|---|---|
| 1 | Not calling removeAll() |
Old lines stay on canvas — trail effect | Always call removeAll() before redrawing |
| 2 | Using getX() instead of getCenter().x |
Line connects to wrong point | Use getCenter() then access .x and .y |
| 3 | Not registering the mouse handler | Nothing happens on mouse move | Call setMouseMoveMethod(yourFunction) |
| 4 | Ball jumps to cursor instantly | No smooth leash feel | Add a distance check — only move if distance > threshold |
| 5 | Follower never stops moving | Overshoots and jitters | Check your distance condition and threshold value |
| 6 | Forgetting this. in class constructor |
Instance variables are lost immediately | Write this.name = name, not just name = name |
| 7 | Dog info not showing through Leash | Undefined or empty output | Check that the Dog object is stored in this.dog and that you call its method correctly |
console.log() to Track CoordinatesWhen your object isn't moving right, print the coordinates to check what's happening.
function mouseMove(e) {
console.log("Mouse X: " + e.getX() + " | Mouse Y: " + e.getY());
// Check if values update on each move
}
Two errors come up most often in this exercise:
getCenter() returned nothing. Check that the object is actually added to the canvas first.NPC companions that follow the player character in RPGs like Stardew Valley use the exact same distance-check logic.
2D game cameras that smoothly follow a character use interpolation — a more advanced version of this exercise.
Drag-and-connect node editors (like in Figma or Blender) use line-following logic to draw connections between elements.
Follower robots use distance sensors and the same leader-follower logic to stay within range of a target robot.
Bone rigs in animation tools use tethered motion — child bones follow parent bones using distance and angle constraints.
The leash exercise teaches a thinking pattern you'll use constantly in computer science:
Recognize this pattern in every future exercise. It will save you hours.
Dog class and a Leash class with object references.removeAll() before redrawing. Every mouse move handler must clear the canvas first, then re-draw all objects and the leash line from scratch. Skipping this leaves old drawings behind.getCenter() return in CodeHS?Point object with two properties: .x and .y. These represent the center of the shape, not the top-left corner. This is important for accurate line drawing.this. in my class constructor?this., the variable is created as a local variable inside the constructor. It disappears as soon as the constructor finishes. The object will have no stored data, and any method trying to access it will get undefined.Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)). This is the standard distance formula based on the Pythagorean theorem. It gives you the straight-line distance in pixels between two canvas points.The 9.7.4 leash codehs exercise teaches a real programming pattern — check, decide, update, repeat. Whether you're doing the JavaScript mouse version or the OOP class version, the core idea is the same: one object follows another, constrained by distance logic.
Don't just copy the code. Understand it. Close this page, open CodeHS, and write it yourself — one line at a time. That's how you build skills that actually last.