Start learning free

LESSON 34 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

React to a Click in JavaScript

Practice

So far your script ran once, top to bottom, when the page loaded. To react to a visitor, you hand the browser a function to call later: an event listener. element.addEventListener("click", fn) means "each time this element is clicked, call fn".

Here is a listener on another element, the heading:

const title = document.querySelector("h1");
title.addEventListener("click", () => {
  console.log("heading clicked");
});

The arrow function does not run at load: addEventListener only registers it. It runs on every click. Inside it, classList.toggle("hidden") removes the class when it is there and adds it when it is not, and classList.contains("hidden") answers true or false.

The footer has a button Show opening hours and a table #hours that starts with the class hidden. The check clicks the button twice and must print:

> click "Show opening hours"
    -   button: Show opening hours
    +   button: Hide opening hours
    +   table "Opening hours"
    +     row: Monday to Friday | 9:00 to 18:00
    +     row: Saturday | 10:00 to 16:00
    +     row: Sunday | Closed
> click "Hide opening hours"
    -   button: Hide opening hours
    -   table "Opening hours"
    -     … its three rows
    +   button: Show opening hours

Your task: find the button #hours-button and the table #hours. Add a click listener to the button that toggles the class hidden on the table, then sets the button's text to Show opening hours when the table is hidden, else Hide opening hours.


Assignment
Follow the Coding Tutorial to find the button and the table, add the click listener, and make the button's text follow the table.


Hint
Ask contains("hidden") after the toggle, not before: you want to know whether the table is hidden now. A ternary, condition ? a : b, picks one of the two texts.


STEP 1 OF 6
    Ctrl + Enter to check

    Dom First Click in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free