← 講座に戻る: JavaScript from scratch

Events and forms

動画は近日公開

An interactive page responds to what the user does: a click, a key press, the submission of a form. Each of these actions generates an event, and your job is to decide which function to run when it happens. The modern way to do it is addEventListener, which receives the event type and a function called a handler (or callback). You can add several handlers to the same element and remove them with removeEventListener.

html
<button id="btn">Click me</button>
<p id="out">Clicks: 0</p>
<script type="module">
  const button = document.querySelector('#btn');
  const out = document.querySelector('#out');
  let clicks = 0;

  button.addEventListener('click', () => {
    clicks++;
    out.textContent = `Clicks: ${clicks}`;
  });
</script>

The event object

The browser passes the handler an object with information about the event. Its most useful properties are target (the element where it happened), key (the key pressed in a keyboard event) and the preventDefault() method, which cancels the browser's default behavior, for example reloading the page when a form is submitted. The most common events are click, input (every change in a field), change, submit, keydown and DOMContentLoaded.

Forms

To read a field use its value property, which is always a string, even if the type is number: convert it with Number when you need to. Listen to the form's submit event, not the button's click, because that way it also works when pressing Enter. Inside the handler call event.preventDefault(), validate the data and show error messages in the DOM itself. Always validate: an empty field or a text where you expected a number is the most normal thing in the world.

html
<form id="form">
  <input id="name" type="text" placeholder="Your name" required />
  <input id="age" type="number" placeholder="Age" />
  <button type="submit">Send</button>
</form>
<p id="message"></p>
<script type="module">
  const form = document.querySelector('#form');
  const message = document.querySelector('#message');

  form.addEventListener('submit', (event) => {
    event.preventDefault(); // do not reload the page
    const name = document.querySelector('#name').value.trim();
    const age = Number(document.querySelector('#age').value);

    if (name === '' || Number.isNaN(age) || age <= 0) {
      message.textContent = 'Please enter a valid name and age.';
      return;
    }
    message.textContent = `Welcome, ${name}! Next year you will be ${age + 1}.`;
    form.reset();
  });
</script>

Event delegation

If you have a list with many elements, adding a handler to each one is costly and does not work for those you create later. The solution is delegation: a single handler on the parent element. Events like click bubble, that is, they go up from child to parent, and with event.target you know which element was clicked. With closest you check whether the click happened inside a specific element. It is the key technique of your final project.

javascript
const list = document.querySelector('#list');

list.addEventListener('click', (event) => {
  const item = event.target.closest('li');
  if (!item || !list.contains(item)) return;
  item.classList.toggle('done');
});

document.addEventListener('keydown', (event) => {
  if (event.key === 'Escape') console.log('Escape pressed');
});

Accessibility and good practices

An interactive page must be usable with a keyboard and screen readers. Use real buttons (button) for actions and links (a) for navigation, instead of a div with a click, because buttons already receive focus and respond to Enter and space. Associate each field with its label using label and the for attribute, and show error messages in a visible element next to the field. Avoid handling the keydown event on the whole document unless it is essential. These small decisions make your application usable by more people and, in addition, simplify your code.

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →