Event Listener


🧩 1. What is an Event Listener?

An event listener is a function that waits for a specific event to happen on a DOM element and executes a callback when it occurs.

Common events include:

  • click → mouse click
  • input / change → form fields
  • keydown / keyup → keyboard
  • submit → form submission
  • mouseover / mouseout → mouse hover

🟢 2. Adding Event Listeners

🔹 Basic Syntax

const button = document.getElementById("myButton");

button?.addEventListener("click", () => {
  console.log("Button clicked!");
});
  • ?. is optional chaining to avoid errors if button is null.
  • "click" is the event type.
  • The second argument is the callback function.

🔹 Using a Named Function

function handleClick() {
  console.log("Button clicked!");
}

button?.addEventListener("click", handleClick);
  • You can remove the listener later using the same function reference:
button?.removeEventListener("click", handleClick);

🟡 3. Event Object

When an event occurs, the listener receives an event object with details about the event.

button?.addEventListener("click", (event) => {
  console.log(event.type);   // "click"
  console.log(event.target); // <button id="myButton">...</button>
});
  • event.target → the element that triggered the event
  • event.currentTarget → the element that the listener is attached to
  • event.preventDefault() → stops default browser behavior
  • event.stopPropagation() → stops event bubbling

🔵 4. TypeScript-Specific Typing

To avoid any errors in TypeScript:

const input = document.querySelector<HTMLInputElement>("#myInput");

input?.addEventListener("input", (event: Event) => {
  const target = event.target as HTMLInputElement;
  console.log(target.value);
});
  • <HTMLInputElement> is a type assertion for the element.
  • event.target as HTMLInputElement tells TS exactly which element it is.

🟣 5. Common Event Types

EventDescriptionCommon Use
clickMouse clickButtons, links
dblclickDouble clickSpecial actions
mouseover / mouseoutMouse hoverTooltips, animations
keydown / keyupKey pressedGame controls, shortcuts
inputValue changesForms
changeInput loses focus after changeForms
submitForm submissionValidation before sending
focus / blurFocus eventsInput highlighting

6. Event Bubbling & Capturing

Events in the DOM bubble from child → parent by default.

const div = document.querySelector("div");
const button = document.querySelector("button");

div?.addEventListener("click", () => console.log("Div clicked"));
button?.addEventListener("click", () => console.log("Button clicked"));
  • Clicking the button logs:
Button clicked
Div clicked
  • To capture in capture phase (parent → child):
div?.addEventListener("click", () => console.log("Div clicked"), true);

🟤 7. Removing Event Listeners

Always use a named function if you want to remove a listener:

function onClick() {
  console.log("Clicked!");
}

button?.addEventListener("click", onClick);
// Later
button?.removeEventListener("click", onClick);

⚠️ Cannot remove an anonymous function.


🟠 8. Tips for TypeScript

  1. Always type your element properly:
const button = document.querySelector<HTMLButtonElement>("#myButton");
  1. Type the event explicitly:
button?.addEventListener("click", (event: MouseEvent) => {
  console.log(event.clientX, event.clientY);
});
  1. Use optional chaining ?. to prevent null errors.

9. Quick Example: Input Listener

const input = document.querySelector<HTMLInputElement>("#name");

input?.addEventListener("input", (event: Event) => {
  const target = event.target as HTMLInputElement;
  console.log("Input value:", target.value);
});
  • Logs every keystroke in the input field.
  • TypeScript ensures target.value exists.

Leave a Reply