Перейти до основного вмісту
← ⚡ JavaScript & the browser·Модуль C2 · Урок 3
ЗавданняHTML has <button id='b'>click me</button>. Add a click listener that logs 'clicked!' to console every time the button is clicked.

addEventListener: натисніть і об’єкт події

75 XP7 min
Теорія

The event-listener pattern

button.addEventListener("click", (event) => {
  console.log("clicked", event.target);
});

Three parts:

  1. The event name — "click", "input", "submit", "keydown", etc.
  2. The handler — your callback. Gets an event argument.
  3. event.target — the element that triggered the event. Useful in delegation (C2-08).

Why addEventListener beats onclick

button.onclick = first;
button.onclick = second;          // first is OVERWRITTEN

button.addEventListener("click", first);
button.addEventListener("click", second);   // BOTH run

onclick = clobbers any previous handler. addEventListener stacks. The latter is the only sane choice in any non-trivial codebase.

removeEventListener — pass the same function

const handler = () => { /* ... */ };
button.addEventListener("click", handler);
button.removeEventListener("click", handler);   // works

If you wrote addEventListener("click", () => { ... }) with an inline arrow, you CAN'T remove it later — there's no reference. Name your handler if you'll need to remove it.

🔒

Зареєструйся щоб кодувати

Теорія відкрита всім. Інтерактивний редактор, живий перегляд і перевірка відкриваються з 7-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.