Please enable JavaScript to use CodeHS

Mouse Events in JavaScript

Learn how to add mouse events to your CodeHS JavaScript programs!

By Rachel Devaney

A mouse event occurs when the user does something with their mouse, like clicking it or moving it. When you clicked on the link to open this tutorial, that was a mouse event. When you hover over a tab and a menu drops down, that’s another mouse event. Mouse events are one of the fundamental ways users interact with programs.

The CodeHS graphics library makes it easy to incorporate mouse events into your graphics programs!

Mouse Clicked

All mouse events use callback functions, which are functions that get called in response to a specific event. To create an event based on a mouse click, we use the mouseClickMethod() with the callback function as the argument.

mouseClickMethod(clickHandler);

function clickHandler(e){
    // code to execute when the user clicks
}
Plain text

This says that every time the user clicks, the function clickHandler is called (or whatever we choose to name the callback function). Notice that we pass the parameter event or e into the callback function. We can use this parameter to get information about the click, such as where the user clicked. The method e.getX() returns the x coordinate of the click, and the method e.getY() returns the y coordinate of the click.

Take a look at the example program below that draws circles where the user clicks. (Learn more about the CodeHS graphics library here.)

  • What happens when you add () to the drawCircle callback function?
  • Look closely at the drawCircle function definition. How does this function use the location of the mouse click to set the position of the circle?

Additional Mouse Methods

Here is a list of all of the other mouse methods you can use in your CodeHS graphics programs:

mouseMoveMethod(callback);
mouseDragMethod(callback);
mouseDownMethod(callback);
mouseUpMethod(callback);

Explore these mouse events by applying them to the Click to Draw Circles example. Change the mouseClickMethod() to other mouse events. How does this change how the user interacts with the program?


Your Turn!

Practice using mouse events in the program below. The starter code creates a circle and adds it to the screen. Use any of the mouse event methods we’ve discussed in this tutorial to complete the following tasks:

  • Increase the radius of the circle by 10 every time the user clicks. (You can use circle.setRadius(radius) to change the radius of the circle.)
  • When the user drags their mouse, have the circle move with it. (You can use circle.setPosition(x, y) to change the position of the circle.)