CodeBlanks Logo Icon CodeBlanks

Click events

JavaScript course · Intermediate · Lesson 32/134

Learn to react to user clicks with the click event.

The click event

click is the most common interface event. It fires when the user clicks an element with the mouse. Most buttons, links and cards work through this event.

const like = document.querySelector('.like');
let count = 0;
like.addEventListener('click', () => {
  count = count + 1;
  console.log(count);
});

Inside the handler you write the code that runs on each click. Increasing a counter, updating text or adding a class happens here. If you declare the variable outside the handler, its value survives between clicks.

Toggling state on click

A common use of the click event is to toggle a state: open/close a menu, add/remove a favorite, mark as read. classList.toggle does this in a single line.

const button = document.querySelector('.menu-button');
button.addEventListener('click', () => {
  const menu = document.querySelector('.menu');
  menu.classList.toggle('open');
});

toggle adds the class if it is missing, and removes it if it is present. So you do not need a separate if. You should remember this from the earlier classList lesson.

Exercise Add a click toggle to the menu button

Select the button with document.querySelector('.menu-button'). Add an arrow function handler with addEventListener('click', ...); inside the handler, select the menu with document.querySelector('.menu') and call classList.toggle('open').

Show example solution
const button = document.querySelector('.menu-button');
button.addEventListener('click', () => {
  const menu = document.querySelector('.menu');
  menu.classList.toggle('open');
});

Test yourself

  1. Which increases the counter by 1 on each click?

    // A
    like.addEventListener('click', () => { count++; });
    // B
    like.addEventListener('count++', () => { click });
    // C
    like.addEventListener(() => { click }, 'count++');
    // D
    like.addEventListener(click, count++);
    • A
    • B
    • C
    • D
    Show answer

    A — Correct! The event type is the 'click' string; the count++ increment happens inside the handler.

  2. Counter-incrementing handler

    let count = 0;
    button.addEventListener('click', () => {
      count = count + ____;
      console.log(count);
    });
    Show answer
    let count = 0;
    button.addEventListener('click', () => {
      count = count + 1;
      console.log(count);
    });
  3. Match the events

    click
    Single click
    dblclick
    Double click
    count++
    Counter increment
    classList.toggle
    Class on/off

All lessons in Intermediate