Interactivity in the browser is entirely driven by events.
The browser fires events when things happen: clicks, key presses, input changes, form submissions, page load. You listen with addEventListener:
button.addEventListener("click", (event) => { ... });The handler receives an event object describing what happened: event.target (the element where it originated), event.key for keyboard events, event.clientX for mouse position, and so on.
Some events have a default action: a link navigates, a form submits and reloads the page. Call event.preventDefault() to stop it, which is what you do when handling a form in JavaScript.
Common events to know:
click,dblclick,pointerdown,pointerupinput(fires on each change to a field) andchange(when the edit is committed)submiton a form — listen here rather than on the button so Enter also workskeydown,keyupDOMContentLoadedondocument,loadonwindow
To remove a listener, call removeEventListener with the same function reference, so keep the handler in a variable. The options object can help: { once: true } removes it after the first call, and { signal } with an AbortController removes it when you call controller.abort().
Avoid inline onclick="..." attributes in HTML; they mix markup and behaviour and run in a confusing scope. Setting el.onclick = fn works but allows only one handler per event.
Read form values with input.value (always a string) or new FormData(form), which collects every named field at once.
Example
// Assumes: <form id="signup"><input name="email"><button>Join</button></form>
// <p id="msg"></p>
const form = document.querySelector("#signup");
const msg = document.querySelector("#msg");
form.addEventListener("submit", (event) => {
event.preventDefault(); // don't reload the page
const data = new FormData(form);
const email = String(data.get("email")).trim();
msg.textContent = email.includes("@") ? `Thanks, ${email}!` : "Invalid email";
});
form.email.addEventListener("input", (e) => {
e.target.classList.toggle("empty", e.target.value === "");
});
function onFirstKey(e) { console.log("first key:", e.key); }
document.addEventListener("keydown", onFirstKey, { once: true });Remember
addEventListener(type, handler)— the handler gets an event objectevent.preventDefault()cancels default actions like form submission- Removing a listener needs the same function reference (or
{ once }/{ signal })
Watch out for
- Listening to a submit button's
clickinstead of the form'ssubmit, so pressing Enter bypasses your code.