CHAPTER 11 · USER INTERACTIONS

JavaScript Events

Events browser me hone wali actions ko represent karte hain — jaise click, typing, key press, focus aur form submit. JavaScript event listeners ke through in actions ka response de sakta hai.

English + Hinglish45 min readPractice included

What is an event?

An event is a signal that something happened in the browser. It may come from the user, the page, or the browser itself.

event.jsJS
const button = document.querySelector("#start-button");

button.addEventListener("click", () => {
  console.log("Button clicked");
});
Hinglish Explanation

Event ko notification samjho. User ne button click kiya, input me type kiya ya key press ki — browser JavaScript ko signal deta hai aur listener wala function run hota hai.

addEventListener()

addEventListener() is the standard way to listen for browser events.

listener.jsJS
const button = document.querySelector("#save-button");

button.addEventListener("click", function () {
  console.log("Saved");
});

The first argument is the event type, and the second is the handler function that runs when the event happens.

Named event handler functions

For reusable or removable listeners, a named function is often clearer.

named-handler.jsJS
const button = document.querySelector("#save-button");

function handleSave() {
  console.log("Saved");
}

button.addEventListener("click", handleSave);
Common mistake: addEventListener("click", handleSave()) function ko immediately call kar deta hai. Listener ko function reference handleSave dena hota hai.

The event object

Browser handler ko an event object passes karta hai. It contains information about what happened.

event-object.jsJS
const button = document.querySelector("#save-button");

button.addEventListener("click", event => {
  console.log(event.type);
  console.log(event.target);
  console.log(event.currentTarget);
});
  • event.type — event ka naam.
  • event.target — actual element jahan event originate hua.
  • event.currentTarget — element jiske listener me handler currently run ho raha hai.

Click events

click buttons, links and other interactive elements ke saath common event hai.

click.jsJS
const toggleButton = document.querySelector("#toggle-details");
const details = document.querySelector("#details");

toggleButton.addEventListener("click", () => {
  details.classList.toggle("is-open");
});
Accessibility: Clickable action ke liye real button use karo. Generic div ko unnecessarily button mat banao.

input and change events

input generally har value change par fire hota hai while the user edits. change commonly value commitment ke baad fire hota hai, depending on the control.

input.jsJS
const search = document.querySelector("#search");

search.addEventListener("input", event => {
  console.log(event.target.value);
});

Live search, character counters and instant feedback ke liye input useful hota hai.

Keyboard events

keydown fires when a key is pressed. keyup fires when it is released.

keyboard.jsJS
const input = document.querySelector("#course-search");

input.addEventListener("keydown", event => {
  if (event.key === "Enter") {
    console.log("Search submitted");
  }
});

Use event.key for the meaning of the pressed key such as "Enter" or "Escape".

Focus and blur

focus runs when an element receives focus and blur when it loses focus.

focus.jsJS
const email = document.querySelector("#email");

email.addEventListener("focus", () => {
  console.log("Email field focused");
});

email.addEventListener("blur", () => {
  console.log("Email field left");
});

Form UX me focus events useful hain, but validation feedback ko sirf blur par depend karna har situation me ideal nahi hota.

Submit events

Form submit ko form element par listen karna chahiye, sirf submit button click ko nahi. Keyboard Enter se bhi form submit ho sakta hai.

submit.jsJS
const form = document.querySelector("#profile-form");

form.addEventListener("submit", event => {
  event.preventDefault();
  console.log("Form handled with JavaScript");
});

Forms aur validation ko next chapter me detail me cover karenge.

preventDefault()

event.preventDefault() browser ke default action ko cancel karta hai when that event is cancelable.

prevent-default.jsJS
const link = document.querySelector("#preview-link");

link.addEventListener("click", event => {
  event.preventDefault();
  console.log("Navigation prevented for this demo");
});
Use intentionally: Default behavior ko bina reason block mat karo. Native browser behavior often accessibility and usability ke liye important hota hai.

Removing event listeners

removeEventListener() works when you pass the same event type and same function reference that was originally registered.

remove-listener.jsJS
const button = document.querySelector("#demo-button");

function handleClick() {
  console.log("Clicked");
}

button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);

Anonymous inline functions ko later remove karna harder hota hai because you no longer have the same function reference.

One-time listeners

The options object can make a listener run only once.

once.jsJS
const button = document.querySelector("#welcome-button");

button.addEventListener("click", () => {
  console.log("Runs one time");
}, { once: true });

Event bubbling

Many events bubble from the target element upward through ancestor elements.

bubbling.jsJS
const card = document.querySelector(".course-card");
const button = document.querySelector(".course-card button");

card.addEventListener("click", () => {
  console.log("Card listener");
});

button.addEventListener("click", () => {
  console.log("Button listener");
});
Simple idea

Button card ke andar hai. Button par click ka event pehle target par hota hai aur phir ancestors ki taraf bubble kar sakta hai. Isliye parent listener bhi run ho sakta hai.

target vs currentTarget

Bubbling samajhne ke liye target aur currentTarget ka difference important hai.

target.jsJS
const list = document.querySelector("#lesson-list");

list.addEventListener("click", event => {
  console.log("target:", event.target);
  console.log("currentTarget:", event.currentTarget);
});

target deepest clicked element ho sakta hai; currentTarget is example me always #lesson-list hoga.

stopPropagation()

stopPropagation() event propagation ko further ancestors tak jane se rok sakta hai.

stop.jsJS
button.addEventListener("click", event => {
  event.stopPropagation();
  console.log("Only this interaction needs to stop bubbling");
});
Use sparingly: Propagation ko habitually stop karna reusable components aur delegation ko break kar sakta hai. Pehle event flow samjho, phir intentional use karo.

Event delegation

Event delegation me parent element par one listener lagaya jata hai aur bubbling ki help se child interactions handle ki jati hain.

delegation.jsJS
const list = document.querySelector("#course-list");

list.addEventListener("click", event => {
  const button = event.target.closest("button[data-course-id]");

  if (!button || !list.contains(button)) return;

  console.log("Course:", button.dataset.courseId);
});

Delegation dynamic elements ke liye especially useful hai because future inserted child buttons bhi parent listener ke through handle ho sakte hain.

mouseenter vs mouseover

mouseover bubbles and may fire when moving between child elements. mouseenter does not bubble in the same way and is often simpler for direct hover-entry logic.

Accessibility caution: Important functionality ko hover-only mat rakho. Keyboard and touch users ko bhi same action available honi chahiye.

Pointer events

pointerdown, pointerup and related pointer events provide a unified model for mouse, touch and pen input in many interactions.

pointer.jsJS
const pad = document.querySelector("#practice-pad");

pad.addEventListener("pointerdown", event => {
  console.log(event.pointerType);
});

Listener options

addEventListener() can receive options such as once, capture and passive.

  • once — automatically removes listener after first run.
  • capture — listener ko capture phase me run kara sakta hai.
  • passive — browser ko batata hai handler certain scrolling-related events me preventDefault() call nahi karega.

Beginner code me defaults usually enough hain; options ko problem ke according use karo.

Events and accessibility

  • Native button, a, input and form controls use karo.
  • Keyboard interaction ko test karo, especially Enter/Space behavior.
  • Mouse-only event handling se important features lock mat karo.
  • Visible focus styles remove mat karo.
  • Dynamic state change ke saath text/ARIA state ko consistent rakho.
  • Unexpected focus movement avoid karo.

Event performance basics

Hundreds of identical child listeners ki jagah suitable cases me delegation useful ho sakta hai. High-frequency events such as scroll, pointermove or input me handler ko lightweight rakho.

Measure first: Performance optimization ko guess mat karo. Beginner projects me readability and correct behavior pehle priority hai.

Common beginner mistakes

  • Handler reference ki jagah handler function immediately call kar dena.
  • event.target aur event.currentTarget confuse karna.
  • Form submit ke bajay sirf button click listen karna.
  • preventDefault() ko unnecessary use karna.
  • Anonymous listener ko later remove karne ki expectation rakhna.
  • Event bubbling ko bug samajh lena.
  • Har jagah stopPropagation() lagana.
  • Hover-only interactions banana.
  • Dynamic children ke liye individual listeners baar-baar attach karna when delegation fits better.

Beginner best practices

  • Event type aur handler ka purpose clear rakho.
  • Reusable handler ko meaningful name do, jaise handleSave.
  • Form ke liye submit event prefer karo.
  • Event object se sirf required data read karo.
  • Delegation use karte waqt closest() and containment check karo.
  • Native browser behavior and semantics preserve karo.
  • Keyboard, mouse and touch usage test karo.

Chapter checklist

  • addEventListener() use kar sakte ho?
  • Event object aur target/currentTarget ka difference clear hai?
  • Click, input, keyboard, focus aur submit events recognize kar sakte ho?
  • preventDefault() ka role samajh aaya?
  • Bubbling aur stopPropagation() ka basic behavior clear hai?
  • Event delegation ka beginner-level pattern use kar sakte ho?
  • Keyboard accessibility ko event handling ke saath consider kar sakte ho?

Practice Task — Interactive Course List

Ek simple course list page banao aur events practice karo.

  1. Button click par message text update karo.
  2. Search input ke input event me current value log karo.
  3. Enter key detect karke search message show karo.
  4. Focus aur blur events console me log karo.
  5. Form ka submit event listen karke controlled demo me preventDefault() use karo.
  6. Event object se type, target aur currentTarget print karo.
  7. Named handler ko add aur remove karke test karo.
  8. { once: true } listener banao.
  9. Parent aur child click listeners se bubbling observe karo.
  10. stopPropagation() ka controlled example test karo aur phir remove karo.
  11. Course list parent par delegation listener lagao.
  12. Dynamic button add karke verify karo ki delegation still works.
  13. Mouse ke bina keyboard se controls test karo.