← All topics

LESSON 09 OF 10

Events and User Input

Respond to clicks and read a visitor’s input.

Before this lesson: complete the preceding lessons or review their examples. No installation or account is needed.

The idea

An event signals something that happened, such as a click or form submission. addEventListener connects an event to a callback. The browser calls that callback when the event occurs.

At a glance

SyntaxPurpose
addEventListener()Register a callback for an event
input.valueRead the field’s current value
.trim()Remove whitespace from both ends of a string

Try it yourself

The preview includes a name field and a Greet me button. Run the code, then type a name and press the button.

Ready. Run the example to open its preview.

Console output

Not run yet.

Page preview

Expected result
No console output yet. Use the Greet me button in the preview.

What to watch for

Pass the function to addEventListener instead of calling it immediately. For a form, listen to submit so Enter also works, and use event.preventDefault() when handling submission without navigation. Native buttons already support keyboard activation.

Your turn

Add a second click listener that logs Greeting requested whenever the button is pressed.

Show one solution
document.querySelector("#greet").addEventListener("click", () => {
  console.log("Greeting requested");
});

Check your understanding

Why use input.value inside the listener?

It reads the current text at click time, including changes made after the script first ran.

Read alongside this lesson

W3Schools: Events and User Input · All learning sources