Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🖱️ Days 8–14 – Data, DOM और Events  ·  दिन 11

दिन 11: Events, Event Object और Delegation

⏱ 95 min📶 Intermediate🎯 100% self-study
दिन 11 / 30

✅ आज आप सीखेंगे

  • addEventListener और सबसे उपयोगी event types
  • Event object: target, key, preventDefault
  • Bubbling, capturing और stopPropagation
  • Event delegation – कई items के लिए एक listener
  • Keyboard shortcuts, once और listeners हटाना

🏢 असली दुनिया में

Product list में 200 मिठाइयाँ हैं। एक junior developer ने 200 अलग click listeners जोड़े – फिर server से नए products आए और उनके buttons बिल्कुल नहीं चले। इलाज event delegation है: parent पर एक listener जो हर मौजूदा और भविष्य के button को संभाले। यह क्लासिक interview सवाल और रोज़ का औज़ार है।

addEventListener और event types

HTML + JavaScript
<button id="b">Click me</button>
<input id="i" placeholder="Type here…" aria-label="Type here">
<select id="s" aria-label="Size"><option>500 g</option><option>1 kg</option></select>
<div id="box" style="margin-top:8px;padding:16px;background:#fef3c7;border-radius:8px">Hover / double-click me</div>
<pre id="log" style="height:110px;overflow:auto;background:#111827;color:#a7f3d0;padding:8px;border-radius:8px"></pre>

<script>
const log = msg => {
  const box = document.querySelector('#log');
  box.textContent = msg + '\n' + box.textContent;
};
document.querySelector('#b').addEventListener('click', () => log('click'));
document.querySelector('#i').addEventListener('input', e => log('input: ' + e.target.value));
document.querySelector('#s').addEventListener('change', e => log('change: ' + e.target.value));
const box = document.querySelector('#box');
box.addEventListener('mouseenter', () => log('mouseenter'));
box.addEventListener('dblclick', () => log('dblclick'));
</script>
▶  Try each control – events appear at the top of the log
Eventकब चलता हैआम उपयोग
clickMouse click, tap, buttons पर Enter/SpaceButtons, cards, menus
inputField में हर keystroke / बदलावLive search, character counters, totals
changeValue पक्की (select, checkbox, blur)Filters, settings
submitForm submitValidate करके fetch से भेजना
keydownKey दबीShortcuts, Esc से बंद
focus / blurField focus पाए / खोएHints दिखाना, छोड़ने पर validate
scroll / resizePage scroll / window resizeSticky effects (throttle करें – Day 24)
DOMContentLoadedHTML parse हुआCode शुरू (defer के साथ ज़रूरी नहीं)

Event object

HTML + JavaScript
<a id="link" href="https://example.com">Go to example.com (blocked)</a>
<p>Press any key while this preview is focused…</p>
<p id="out"></p>

<script>
document.querySelector('#link').addEventListener('click', function (event) {
  event.preventDefault();                       // stop the default action (navigation)
  document.querySelector('#out').textContent = `Link click stopped. target: <${event.target.tagName.toLowerCase()}>`;
});
document.addEventListener('keydown', e => {
  document.querySelector('#out').textContent =
    `key: "${e.key}"  code: ${e.code}  ctrl: ${e.ctrlKey}  shift: ${e.shiftKey}`;
});
</script>
▶  event.preventDefault(), event.target and keyboard details
Property / methodमतलब
e.targetजिस element पर असल में click/type हुआ
e.currentTargetजिस element पर listener लगा है
e.preventDefault()Default व्यवहार रोकें (form submit reload, link navigation)
e.stopPropagation()Parents तक bubbling रोकें (कम इस्तेमाल)
e.key / e.codeकौन सी key ("Enter", "Escape", "a")
e.ctrlKey / shiftKey / metaKeyShortcuts के लिए modifier keys

Bubbling: events ऊपर जाते हैं

HTML + JavaScript
<div id="outer" style="padding:16px;background:#e0e7ff;border-radius:10px">outer div
  <div id="inner" style="padding:16px;background:#c7d2fe;border-radius:10px;margin-top:6px">inner div
    <button id="btn">button</button>
  </div>
</div>
<p id="path"></p>

<script>
const path = [];
['#btn', '#inner', '#outer'].forEach(sel => {
  document.querySelector(sel).addEventListener('click', e => {
    path.push(e.currentTarget.id);
    document.querySelector('#path').textContent = 'Order: ' + path.join(' → ');
  });
});
document.querySelector('#btn').addEventListener('click', () => { path.length = 0; }, { capture: true });
</script>
▶  Click the button: btn → inner → outer

Event delegation – professional pattern

HTML + JavaScript
<ul id="products"></ul>
<button id="more">Load 2 more products</button>
<p id="cart">Cart: 0 items</p>

<script>
const all = ['Kaju Katli', 'Ghewar', 'Rasmalai', 'Ladoo', 'Kalakand', 'Soan Papdi'];
let shown = 2, cartCount = 0;
const list = document.querySelector('#products');

function render() {
  list.innerHTML = all.slice(0, shown).map((name, i) =>
    `<li>${name} <button data-action="add" data-index="${i}">Add</button>
                  <button data-action="info" data-index="${i}">Info</button></li>`).join('');
}

// ONE listener on the parent handles every button – even ones added later
list.addEventListener('click', e => {
  const btn = e.target.closest('button[data-action]');
  if (!btn) return;                                  // click was not on a button
  const name = all[Number(btn.dataset.index)];
  if (btn.dataset.action === 'add') {
    cartCount++;
    document.querySelector('#cart').textContent = `Cart: ${cartCount} items (last: ${name})`;
  } else {
    alert(`${name}: made fresh every morning`);
  }
});
document.querySelector('#more').addEventListener('click', () => { shown = Math.min(all.length, shown + 2); render(); });
render();
</script>
▶  New buttons work immediately because the parent listens
  1. 1एक स्थिर parent (list, table, document) पर एक listener लगाएँ
  2. 2Handler में e.target.closest(selector) से असली target ढूँढें
  3. 3कुछ न मिले तो जल्दी return
  4. 4कौन सा item और कौन सा action – data-* से पढ़ें
  5. 5बाद में render हुए items के लिए भी चलता है – और कम memory
Delegation का तरीक़ा

Keyboard shortcuts, once और listeners हटाना

HTML + JavaScript
<button id="open">Open offer</button>
<div id="modal" hidden style="margin-top:10px;padding:16px;border:2px solid #ca8a04;border-radius:12px">🎁 10% off today! <small>(press Esc or click ✕)</small> <button id="x" aria-label="Close">✕</button></div>
<p><button id="once">Claim coupon (works once)</button> <span id="c"></span></p>

<script>
const modal = document.querySelector('#modal');
function onKey(e) { if (e.key === 'Escape') close(); }
function open() { modal.hidden = false; document.addEventListener('keydown', onKey); }
function close() { modal.hidden = true; document.removeEventListener('keydown', onKey); }   // same function reference!
document.querySelector('#open').addEventListener('click', open);
document.querySelector('#x').addEventListener('click', close);

document.querySelector('#once').addEventListener('click', () => {
  document.querySelector('#c').textContent = 'Coupon SWEET10 applied ✅';
}, { once: true });
</script>
▶  Esc closes the offer; the coupon button only works the first time
⚠️ removeEventListener को वही function चाहिए

Anonymous arrow function हटाया नहीं जा सकता, क्योंकि दोबारा लिखने पर नया function बनता है। हटाना हो तो named function (जैसे onKey) में रखें।

🏅 आज के Job Skills

✔ click, input, change, submit और key events सुनना✔ Event object और preventDefault✔ Bubbling समझना और event delegation✔ Shortcuts, एक-बार listeners और सफ़ाई

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: Star rating बनाएँ: एक container में 5 ★ buttons; तीसरे पर click से पहले तीन सुनहरे। Delegation लें।
Solution देखें
▶  Result
Task 2: Keyboard shortcut जोड़ें: "/" दबाने पर search box पर focus (पर दूसरे input में लिखते समय नहीं)।
Task 3: Orders की table में एक listener से 🗑 button पर click होने पर row delete करें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. Form को page reload करने से रोकें:
Default action रुकता है।
2. Input के हर keystroke का event:
change पक्के होने का इंतज़ार करता है।
3. Div के अंदर button click के बाद div का click listener…
Events ऊपर जाते हैं।
4. Event delegation का मतलब…
Bubbling इस्तेमाल करता है।
5. { once: true } listener को…
अपने-आप हटता है।

Interview corner

💼 Interview Corner

Event bubbling और delegation समझाइए।

Target पर event होने के बाद वह ancestors से ऊपर जाता है (bubbling)। Delegation साझा ancestor पर एक listener लगाकर e.target/closest से तय करता है किस child ने trigger किया – लंबी या dynamic lists के लिए कुशल।

e.target बनाम e.currentTarget?

target वह सबसे अंदर का element है जहाँ event शुरू हुआ; currentTarget वह element है जिसका listener अभी चल रहा है (जिस पर आपने लगाया)।

सारांश

  • el.addEventListener("click", handler) – कई event types।
  • e.target, e.key और e.preventDefault() रोज़ के helpers।
  • Events bubble होते हैं; delegation = parent पर एक listener + closest()।
  • सफ़ाई के लिए once, named handlers और removeEventListener।
➡️ आगे

Day 12: elements बनाना और data से lists render करना – React वाला data → UI pattern।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

onclick attribute या addEventListener?
addEventListener: कई listeners जोड़ सकते हैं, हटा सकते हैं, once/passive जैसे options, और JS को HTML से अलग रखते हैं।
क्या phones पर clicks चलते हैं?
हाँ, taps click events चलाते हैं। Buttons के लिए असली <button> elements लें ताकि keyboard और screen-reader users भी चला सकें।
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 12: Elements बनाना और Data से Lists Render आपकी प्रगति: 11 / 30 (37%) · Lesson 12 / 30 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें