Course contentsLesson 4 of 6← Course overview
  1. 01A page is a conversation18 min
  2. 02Give your content structure24 min
  3. 03Make a layout that adapts32 min
  4. 04Make a button do something35 min
  5. 05Make forms easier to use28 min
  6. 06Keep a trail of your work36 min

Web development · Lesson 04

Make a button do something

Edit lesson

Connect a user action to a small, understandable response.

35 minProgress saves on this device
In this lesson
  • Find an element with JavaScript
  • Respond to a click with an event listener

Helpful background: Basic HTML and a little JavaScript syntax.

Behavior starts with an event

A browser can report events such as clicks, typing, and form submission. JavaScript can listen for an event and run a function in response.

Keep the first interaction small

Find one element, listen for one event, and update one part of the page. Small steps make it easier to see what your code is doing and to debug it.

Explain what changed

A clear interface tells the user that an action worked. Update text, show a message, or change a visible state instead of leaving the result hidden.

Listen for a clickjs
const button = document.querySelector('#hello');
const message = document.querySelector('#message');

button.addEventListener('click', () => {
  message.textContent = 'Nice work — your event ran.';
});
Knowledge check

What does addEventListener help your code do?

Try first; feedback appears after you check.
Apply it

Your turn

Describe what should happen when a learner clicks a “Show tip” button. Which two page elements would your script need?

Continue readingMDN: Events

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson