9.7.4 Leash CodeHS Answers: Step-by-Step Guide

9.7.4 Leash CodeHS Answers: Step-by-Step Guide

You run your code, move the mouse, and nothing happens. The ball sits still. The line stays frozen. Many students hit this wall in the 9.7.4 leash exercise. The good news is that the fix is small. This guide gives you the working code, a clear code walkthrough, and simple fixes for common coding errors. You will also see why each line matters. So let’s build this CodeHS exercise step by step and make the ball follow the mouse the right way.

What Is the 9.7.4 Leash CodeHS Exercise?

The 9.7.4 Leash task is a CodeHS JavaScript exercise about mouse movement. You build a small graphics program with two parts. One part is a ball object. Another part is a line object that works like a leash. At the start, the line sits in the center of the canvas. Then the ball follows the cursor. As you move the mouse, the line stretches and keeps touching the ball. So the leash always joins the center point to the ball. This coding exercise looks simple. However, it teaches event-driven programming in a clear and visual way.

Most students meet this programming assignment in the Introduction to Computer Science in JavaScript course. It is a student programming exercise that checks three skills. First, you create graphical objects. Next, you add them to the screen. Finally, you update them when the user moves the mouse. Each skill builds on the last one. Because the program reacts in real time, you see your result right away. That quick feedback makes this JavaScript graphics exercise a great coding practice task for beginners.

What the Number 9.7.4 Means in the CodeHS Course

The numbers follow the CodeHS course layout. The first number points to the unit or module. The second number points to the lesson. The last number points to the exercise inside that lesson. So 9.7.4 means unit 9, lesson 7, exercise 4. Your own course page may use slightly different titles, because CodeHS updates its curriculum from time to time. Still, this pattern helps you find any CodeHS assignment fast.

Exercise points also matter in this course. Your teacher may use them to track progress, and the grader checks your result against the exercise requirements. If your output misses one detail, you can lose points. For example, a missing line or a wrong ball color can fail a check. So read the instructions slowly before you type. Then match each requirement with one line of JavaScript code. This habit saves time and cuts down on guesswork.

9.7.4 Leash CodeHS Answers: The Working Code

Here is the working solution for the 9.7.4 leash exercise. It uses the start function, one event handler, and two global objects. Copy it only to check your own work. Then type it again line by line so you remember each step. Your assignment may ask for a different color or size, so match your own instructions. This step-by-step solution gives you a clean base to compare against.

javascript

var BALL_RADIUS = 20;
var ball;
var line;

function start() {
    var centerX = getWidth() / 2;
    var centerY = getHeight() / 2;

    line = new Line(centerX, centerY, centerX, centerY);
    add(line);

    ball = new Circle(BALL_RADIUS);
    ball.setColor(Color.yellow);
    ball.setPosition(centerX, centerY);
    add(ball);

    mouseMoveMethod(updateLeash);
}

function updateLeash(e) {
    ball.setPosition(e.getX(), e.getY());
    line.setEndpoint(e.getX(), e.getY());
}

This code has two jobs. The start function builds the scene once. The updateLeash function runs each time the mouse moves. Because of this split, the program stays short and clean. It is the correct solution pattern for most versions of this task. This setup also shows the core idea of event-driven programming. You write the reaction once, and CodeHS calls it again and again as the user moves the cursor.

Code Walkthrough: How the Solution Works

Step 1: Set Up the Variables and BALL_RADIUS

Every good program starts with its data. Here, the top three lines declare BALL_RADIUS, ball, and line. BALL_RADIUS holds the size of the ball. A name in capital letters tells readers that the value never changes. Also, the ball and line variables sit outside every function. That spot gives them global scope. As a result, both the start function and the update function can reach them. This detail matters because the event handler runs later, after start has finished.

Some students declare the ball inside start with var. Then the handler cannot see it, and the console shows a “not defined” error. So keep the declaration at the top. You can still assign the objects inside start, and the whole program works. This pattern is the heart of object initialization in CodeHS graphics programming. You declare early, you initialize objects once, and you reuse them everywhere.

Step 2: Find the Center Point and Create the Line

Next, the code finds the middle of the canvas. The getWidth function returns the canvas width, and getHeight returns the height. Half of each value gives you centerX and centerY. Then the code creates the line object with four numbers. The first pair marks where the line starts. The second pair marks where it ends. At the beginning, both pairs match, so the line has no length. After that, add(line) puts the object on the screen. Without this call, nothing appears.

The center point stays fixed. In other words, it anchors the leash like a hook on a wall. Only the line endpoint moves later. This idea matters because beginners often move both ends by mistake. Then the line turns into a short dash that chases the mouse. Keep the start fixed, and the leash looks right. This is also the simplest way to practice drawing lines on a canvas with real purpose.

Step 3: Create the Ball and Register the Mouse Event

Now the code makes the ball object. The Circle constructor takes the ball radius, so new Circle(BALL_RADIUS) gives you a ball of size 20. Then setColor paints it yellow, and setPosition places it at the center point. After that, add(ball) draws it on the canvas. Notice the order. The code adds the line first and the ball second. This order puts the ball on top of the line, so the leash looks attached to the ball.

Finally, the start function calls mouseMoveMethod(updateLeash). This single line registers the mouse event handler. From now on, CodeHS calls updateLeash each time the cursor moves. You do not call it yourself. Also, you pass the function name without parentheses. If you write updateLeash(), JavaScript runs it right away and passes the result instead. That mistake breaks the exercise, and the ball never moves.

Step 4: Move the Ball and Update the Line

The updateLeash function holds the real action. It takes one parameter, often named e. This event object stores the cursor position. The e.getX() call returns the horizontal value, and e.getY() returns the vertical value. First, the function moves the ball with setPosition. Then it stretches the line with setEndpoint. Both calls use the same two numbers. So the ball and the line endpoint land on the exact same spot. The ball center also sits right under the pointer, which gives you simple cursor centering.

This step shows state synchronization in a small form. Two objects must always agree about one position. If you update only the ball, the line stays frozen. If you update only the line, the ball sits still while the leash points at empty space. So change both objects inside the same function. When you trace the program flow, you see a clear loop: the mouse moves, the handler runs, and both objects update. The ball follows the mouse, the line follows the mouse, and the leash looks smooth.

Mouse Events and Canvas Coordinates Explained

A mouse move event fires whenever the cursor changes position over the canvas. CodeHS packs the details into an event object, and your function receives it. From that object, you read the cursor position with getX and getY. These numbers use canvas coordinates on the JavaScript canvas. The origin sits at the top-left corner. The X value grows as you move right. The Y value grows as you move down. So a point near the bottom has a large Y value. This simple mouse tracking pattern powers many interactive graphics.

The table below sums up the main calls in this exercise. Keep it nearby while you code. Each row matches one line in the solution. After a few tries, you will write these calls from memory.

CallWhat it doesWhere you use it
mouseMoveMethod(fn)Registers the mouse event handlerInside start
e.getX() and e.getY()Read the cursor positionInside updateLeash
ball.setPosition(x, y)Moves the ball centerInside start and updateLeash
line.setEndpoint(x, y)Moves the line endpointInside updateLeash
add(object)Adds the object to the canvasInside start

Why the Y-Axis Feels Upside Down

Math class draws the Y-axis with positive values going up. A computer canvas does the opposite. This inverted Y-axis surprises many beginners. When you move the mouse up, the Y value gets smaller. When you move it down, the value gets larger. However, you do not need extra math in this exercise. The cursor and the canvas use the same system, so the ball lands right under the pointer.

The trouble starts when you mix systems. For example, some students subtract the mouse Y value from the canvas height to flip it. Then the ball moves in the opposite direction, and it looks like a teleporting ball. Use the raw getX and getY numbers, and the problem goes away. Save the flipping idea for graphs and charts, where the axis rules change.

Why Global Scope and Single Creation Matter

A common beginner habit is to create new objects inside the handler. For example, a student writes new Circle and add(ball) inside updateLeash. Then each tiny mouse move adds another ball. After a few seconds, the screen holds hundreds of circles and lines. The program slows down, and the picture looks like a messy trail. So build each object once in the start function. Then only change its position later. This approach is the safe way to handle object initialization, and it keeps the program flow easy to read.

Think of the ball as a puppet. You build the puppet once, and then you move its strings. You do not build a new puppet for every motion. In the same way, the ball and the line already exist when the handler runs. The handler just updates their state. This habit also helps in bigger projects, such as animation and games, where hundreds of objects share the same screen.

Common Coding Errors and How to Fix Them

Even a short program can break in small ways. Most of the common mistakes in the Leash CodeHS task fall into a few groups. The table below lists the usual signs, causes, and fixes. Use it as a quick troubleshooting guide before you rewrite any code.

ProblemLikely causeFix
The ball does not moveThe handler is missing or misspelledCall mouseMoveMethod(updateLeash) in start
The ball moves, but the leash stays frozenThe setEndpoint call is missingAdd line.setEndpoint(e.getX(), e.getY())
The console shows an undefined variableVariables sit inside startMove var ball and var line to the top
Nothing appears on the canvasadd(ball) or add(line) is missingAdd both objects to the canvas
The ball jumps to odd spotsThe Y value is flipped or the math is wrongUse the raw getX and getY numbers
Hundreds of circles appearObjects are created inside the handlerCreate each object once in start
A syntax error shows upA bracket, brace, or quote is missingMatch every opening and closing pair

Read the console message first. It names the line number and the kind of error. For instance, a message about a missing brace points near the end of your function. Fix one error at a time, and then run the program again. This method beats random changes. It also builds real skill in debugging JavaScript, which you will use in every later project.

How to Test and Debug Your Leash Program

Testing takes less than a minute. Run the program, and then move the mouse in slow circles. Watch the ball and the line together. They should move as one unit. Next, move the mouse fast toward the edges of the canvas. The ball should still follow without gaps. Also, bring the mouse back to the center. The line should shrink to almost nothing. If a test fails, you know which part to inspect. You can also print the cursor position inside updateLeash to check the numbers.

Use these quick checks before you submit your work:

  • The line starts at the center of the canvas.
  • The ball follows the cursor at all times.
  • The line endpoint always touches the ball.
  • The ball has the right color and radius.
  • No extra objects appear on the screen.

Compare your result with the exercise requirements one more time. A correct solution passes each check without extra code. If you still see common mistakes, go back to the table above and match your symptom with its fix.

Take It Further: Limited Distance Movement

Once the basic version works, you can try a tougher version. A real leash has a fixed length, so the follower object cannot run far from the leader object. Here, the cursor acts as the leader, and the ball acts as the follower. Now you need a distance calculation. Measure how far the cursor sits from the center point. If the distance stays below the leash length, place the ball at the cursor. Otherwise, move the follower closer to the center point along the same direction. This gives you limited distance movement.

javascript

var LEASH_LENGTH = 150;

function updateLeash(e) {
    var dx = e.getX() - getWidth() / 2;
    var dy = e.getY() - getHeight() / 2;
    var distance = Math.sqrt(dx * dx + dy * dy);

    if (distance > LEASH_LENGTH) {
        dx = dx * LEASH_LENGTH / distance;
        dy = dy * LEASH_LENGTH / distance;
    }

    ball.setPosition(getWidth() / 2 + dx, getHeight() / 2 + dy);
    line.setEndpoint(getWidth() / 2 + dx, getHeight() / 2 + dy);
}

This extra code is optional, and your assignment may not ask for it. Still, it shows how geometry connects to graphics programming. The offset keeps the same direction but gets shorter, so the ball stops at the end of the leash. Try changing LEASH_LENGTH and watch the result. Small experiments like this turn one exercise into real coding practice.

What the Leash Exercise Teaches You

This small task covers many programming concepts. You practice variables, functions, parameters, and objects in one short program. You also learn how a program reacts to user input in real time. In addition, you see how the order of your code changes the final picture. The same pattern shows up in interactive JavaScript graphics, drawing apps, and simple games. For example, a game might aim a laser line toward the cursor or drag a tool along a path.

Beyond the code, the exercise teaches a good habit. You break a problem into small parts, test each part, and fix one issue at a time. That habit helps in every course after this one. Because the result appears on screen, you get quick proof of progress. As a result, mouse tracking feels less like theory and more like play. Keep practicing with new ideas, such as a second ball, a color change, or a click event.

Conclusion

The 9.7.4 leash exercise looks small, but it holds a lot of lessons. You declare global variables, build a line and a ball once, and register a mouse event handler. Then the updateLeash function moves both objects with the same cursor position. That is the whole solution. If your program fails, check the handler name, the global scope, and the setEndpoint call first. This complete guide gives you every piece you need to fix the usual problems.

Use this guide as a map, not a shortcut. Type the code yourself, break it on purpose, and fix it again. That practice turns a CodeHS answer into real skill. Try the leash length idea next, and share your progress with classmates. You will find that each new CodeHS exercise feels easier than the last.

FAQs

What is the 9.7.4 Leash exercise in CodeHS?

It is a JavaScript graphics exercise. You make a ball follow the mouse while a line connects the ball to the center of the canvas. The task teaches mouse events, objects, and functions in one short program.

Why does the ball not follow my mouse?

You probably did not register the handler. Call mouseMoveMethod(updateLeash) inside the start function, and use the exact function name without parentheses. Also check that the ball sits in global scope and that you added it to the canvas.

Why does the line not stretch with the ball?

You likely skipped the setEndpoint call. Inside the handler, call line.setEndpoint(e.getX(), e.getY()). Use the same numbers that you use for the ball position, so both objects stay in sync.

Should I create the ball and line inside the mouse function?

No. Create both objects once in the start function. The handler should only update their positions. Otherwise, the program adds a new object with every mouse move, and the screen fills with copies.

How do I find the center of the canvas in CodeHS?

Use getWidth() / 2 for the center X value and getHeight() / 2 for the center Y value. These two numbers give you the exact center point of the canvas.

Also Read: Glaadvoice.com Review: Is It Really Legit and Safe Now?

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *