Event Handling (addEventListener & Event Delegation)
Using Only addEventListener
The HTML has no inline event attributes like onclick; every event is wired up with addEventListener inside the bindEvents() function in main.js.
onclick | addEventListener | |
|---|---|---|
| Registering several for the same event | Only one possible; later code overwrites it | Safely adds multiple handlers |
| Separating structure and behavior | JS gets mixed into the HTML | HTML (structure) and JS (behavior) stay separate |
Event Delegation
Instead of attaching a listener to every single link or button, you attach it only once to the parent element and handle events there. In this project it was used in two places.
js
// Menu link click → automatically close the mobile menu
selectors.menu.addEventListener('click', (event) => {
if (event.target.matches('a')) {
setMenuState(false);
}
});
// Filter button click → apply the language filter (buttons created later also work automatically)
selectors.filterGroup.addEventListener('click', (event) => {
const button = event.target.closest('[data-filter]');
if (button) {
applyProjectFilter(button.dataset.filter);
}
});The filter buttons are created dynamically after the API response arrives, so with a listener on the parent, there's no need to wire them up separately even when new buttons appear.
Summary
- All events are wired up with
addEventListenerin one place,bindEvents() - Repeated elements and elements created later are handled from the parent through event delegation
Source: Codyssey-B1/B1-1
