CodeBlanks Logo Icon CodeBlanks

Mouse events

JavaScript course · Intermediate · Lesson 33/134

Learn to track mouse movement with mouseover, mouseout and mousemove.

mouseover and mouseout

When the mouse enters an element, mouseover fires; when it leaves, mouseout fires. These two are the basic tools for hover effects.

const card = document.querySelector('.card');
card.addEventListener('mouseover', () => {
  card.classList.add('hover');
});
card.addEventListener('mouseout', () => {
  card.classList.remove('hover');
});

You add the two listeners separately: one adds the class on enter, the other removes it on leave. You can call addEventListener many times on the same element; all listeners run.

mousemove and coordinates

While the mouse moves over an element, the mousemove event fires very frequently. Its event.clientX and event.clientY properties give the mouse position in the viewport.

const area = document.querySelector('.area');
area.addEventListener('mousemove', (event) => {
  console.log(event.clientX, event.clientY);
});

Coordinates start from the top-left corner of the window. Because it fires so often, you avoid heavy work in it; but for simple position tracking it is ideal.

Exercise Toggle a class on mouse enter and leave

Select the card element with document.querySelector('.card'). Add an arrow function handler for the mouseover event that calls classList.add('hover'); add another handler for mouseout that calls classList.remove('hover').

Show example solution
const card = document.querySelector('.card');
card.addEventListener('mouseover', () => {
  card.classList.add('hover');
});
card.addEventListener('mouseout', () => {
  card.classList.remove('hover');
});

Test yourself

  1. Which event fires when the mouse enters an element?

    • mouseout
    • mouseover
    • mousemove
    • mousedown
    Show answer

    mouseover — Correct! mouseover fires when the mouse enters the element.

  2. Complete the mouseover listener

    card.addEventListener('____', () => {
      card.classList.add('hover');
    });
    Show answer
    card.addEventListener('mouseover', () => {
      card.classList.add('hover');
    });
  3. Match the mouse events

    mouseover
    On enter
    mouseout
    On leave
    mousemove
    On move
    clientX
    Horizontal coordinate

All lessons in Intermediate