Events and the DOM
Beyond reading the DOM, real pages react to what the user does, clicks, typing, submitting forms, through events.
const button = document.querySelector('#save');
button.addEventListener('click', (event) => {
event.preventDefault();
console.log('Saved!');
});
const input = document.querySelector('#name');
input.addEventListener('input', (event) => {
console.log('Typing:', event.target.value);
});
This needs a real web page with a #save button and #name input, so it's read-only here, you'll wire up real event handlers in the final project.
Key ideas
addEventListener(type, handler)attaches a handler for an event type ('click','input','submit', and many more) without overwriting any handlers already attached.- The
eventobject passed to your handler describes what happened,event.targetis the element the event fired on,event.target.valuereads an input's current text. event.preventDefault()stops the browser's default behavior, most commonly used to stop a form from reloading the page on submit.