Event Listeners
Respond to user actions — click, input, submit, keyboard events
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
s let your code respond to user interactions and browser events.
element.addEventListener('click', handler);
element.removeEventListener('click', handler);The event object:
javascript button.addEventListener('click', (event) => { console.log(event.target); // element that was clicked console.log(event.type); // 'click' event.preventDefault(); // stop default browser behavior });
Common events: click, dblclick, mouseenter, mouseleave, keydown, keyup, input, change, submit, focus, blur, scroll, resize
Event delegation — attach ONE listener to a parent instead of many to children: ``javascript document.querySelector('ul').addEventListener('click', (e) => { if (e.target.tagName === 'LI') { console.log('Clicked:', e.target.textContent); } });
Event propagation: Events bubble up from the target to the root. stopPropagation() prevents this.
Once option:
javascript el.addEventListener('click', handler, { once: true }); // Automatically removed after first trigger
Examples
Form submission
preventDefault() is essential on form submit to stop page navigation
document.querySelector('#signup-form').addEventListener('submit', (e) => {
e.preventDefault(); // stop page reload
const email = e.target.querySelector('input[name=email]').value;
console.log('Submitting:', email);
});Event delegation for a dynamic list
Delegation handles dynamically added elements automatically
const list = document.querySelector('#todo-list');
list.addEventListener('click', (e) => {
const item = e.target.closest('li');
if (item) item.classList.toggle('done');
});
// Works even for LI elements added after this code runsHow well did you understand this?
Next in JavaScript Core
Fetch API