Event handling basics

Computer Science · JavaScript

Question 1 of 10

0

    To read the printed key, such as 'a' or 'Enter', from a keyboard event, use:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Event handling basics explained

    Events are signals that something happened, such as a click, a key press or a form submission. A handler is a function that JavaScript runs in response, and it is how a page reacts to the user.

    Attach a handler with addEventListener, passing the event name and a function. The function receives an event object. Its target property is the element that triggered the event. preventDefault stops the browser's default action, such as following a link, and stopPropagation stops the event from travelling further.

    const list = document.querySelector("#todo");
    list.addEventListener("click", (event) => {
        if (event.target.tagName === "LI") {
            console.log("Clicked:", event.target.textContent);
        }
    });
    

    By default events bubble: an event on a child element runs its handlers and then the handlers of each ancestor. This allows event delegation, where one listener on a parent handles clicks on all its children by checking event.target. removeEventListener needs the same function reference, so use a named function.

    Worked example

    The list has three items. A user clicks the second one. The click bubbles up to the ul, the handler runs once, and event.target is that li, so the log prints its text. A click on the list's own padding, between the items, has target UL, so nothing is logged.

    What you will practise

    104 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • Events include:
    • addEventListener:
    • An event object:
    • preventDefault():
    • Event bubbling:
    • The click event fires when:
    • Which method removes an event listener?
    • Inside a listener, which event property refers to the element the listener is attached to?

    …and 96 more.