Events are how web pages react to people.
Direct answer
Use element.addEventListener(type, handler) to run a function when an event happens. Common types are click, input, submit, keydown and mouseover. The handler receives an event object with details such as the target element.
Basic example
<button id="btn">Click me</button>
<script>
const btn = document.querySelector("#btn");
btn.addEventListener("click", () => {
alert("Clicked!");
});
</script>
The event object
input.addEventListener("input", (event) => {
console.log(event.target.value);
});
Removing listeners
function onClick() { console.log("hi"); }
btn.addEventListener("click", onClick);
btn.removeEventListener("click", onClick);
You must pass the same function reference, so avoid anonymous functions if you need to remove it.
Handy options
btn.addEventListener("click", onClick, { once: true });
Where Teyro fits
Teyro's Interactive Web Pages with JavaScript course turns this into short lessons you can play in a few minutes a day. It has 37 lessons, and you can start free.
The bottom line
Select an element, listen for an event, run a function. That pattern powers nearly every interactive page.



