Monday, July 14, 2025

Javascript Module 32

  Module 32 : Event Handling Basics 

๐Ÿง  1. What is an Event in JavaScript?

In JavaScript, an event is a signal that something has happened in the DOM (Document Object Model). This could be a user interaction (click, keypress, mousemove) or a browser-triggered action (load, resize, scroll).

JavaScript uses event-driven programming, where code responds to events as they occur.





๐Ÿ” Insight : Event-driven programming is essential in UI development because it allows for dynamic user interactions without constant polling or refreshing.


 2. Types of Events

Event Category

Examples

Mouse Events

click, dblclick, mousedown, mouseup, mouseenter, mouseleave, mousemove

Keyboard Events

keydown, keyup, keypress

Form Events

submit, change, focus, blur, input

Window Events

load, resize, scroll, unload

Touch Events

touchstart, touchend, touchmove (for mobile)



 3. Methods to Handle Events

✅ 3.1 Inline Event Handlers (Not Recommended)

html code

<button onclick="alert('Button clicked!')">Click Me</button>

๐Ÿ”Ž Drawback: Hard to manage, not scalable, mixes HTML and JS.


✅ 3.2 DOM Property Method

javascript code

const btn = document.getElementById('myBtn'); btn.onclick = function () { alert('Clicked!'); };

⚠️ Limitation: Overwrites previous handlers. Only one event handler per type.


✅ 3.3 addEventListener() Method (Best Practice)

javascript code

const btn = document.getElementById('myBtn'); btn.addEventListener('click', function () { alert('Using addEventListener!'); });

✅ Advantages:

Can register multiple handlers

Supports removing handlers

Works with event capturing and bubbling


 4. The Event Object

When an event occurs, JavaScript creates an event object containing details about the event.








javascript code

btn.addEventListener('click', function (event) { console.log(event.type); // 'click' console.log(event.target); // element clicked });

๐Ÿง  Event Object Properties:

type – type of event (click, submit, etc.)

target – the DOM element where event happened

preventDefault() – prevents default action

stopPropagation() – stops event bubbling


 5. Event Propagation: Bubbling vs Capturing

๐Ÿ” Bubbling (Default):

The event starts from the target element and bubbles up to ancestors.

javascript code

document.getElementById('child').addEventListener('click', () => { alert('Child clicked'); }); document.getElementById('parent').addEventListener('click', () => { alert('Parent clicked'); });

Clicking child → triggers both child and parent handlers (child first).

↕ Capturing (Optional):

javascript code

parent.addEventListener('click', () => { alert('Captured at parent'); }, true); // true = capture phase

Capturing → top-down; Bubbling → bottom-up.


 6. Removing Event Handlers

javascript code

function handleClick() { alert('Once only!'); btn.removeEventListener('click', handleClick); } btn.addEventListener('click', handleClick);


7. Event Delegation

Event delegation uses bubbling to handle events on parent elements, improving performance in dynamic lists.

javascript code

document.getElementById('list').addEventListener('click', function (event) { if (event.target.tagName === 'LI') { alert('Item: ' + event.target.innerText); } });

๐Ÿ” Use Case: Efficient when managing many child elements (e.g., dynamic todo list items).


 8. Exercises













๐Ÿ’ก Example 1: Button Click Alert

html code

<button id="clickBtn">Click Me</button> <script> document.getElementById('clickBtn').addEventListener('click', () => { alert('Hello, JavaScript!'); }); </script>

Objective: Understand addEventListener.


๐Ÿ’ก Example 2: Preventing Form Submission

html code

<form id="myForm"> <input type="text" name="name" required /> <button type="submit">Submit</button> </form> <script> document.getElementById('myForm').addEventListener('submit', function (e) { e.preventDefault(); alert('Form submission stopped for validation.'); }); </script>

Objective: Learn preventDefault().


๐Ÿ’ก Example 3: Keyboard Interaction

javascript code

document.addEventListener('keydown', function (e) { if (e.key === 'Enter') { alert('Enter key pressed'); } });

Objective: Understand keyboard event handling.


๐Ÿ’ก Exercise 1: Toggle Background Color on Button Click

Create a button. When clicked, toggle the background color between red and green.

๐Ÿ”ง Hint:

javascript code

btn.classList.toggle('active');


๐Ÿ’ก Exercise 2: Add Item to List

Input field + button.

On button click, append input value to a list using createElement.


๐ŸŽ“  Tips

๐Ÿง  Start with analogies (e.g., “pressing a doorbell” as an event).

๐Ÿงช Use browser console demos to show addEventListener() in real time.

๐ŸŽจ Visualize bubbling vs capturing using nested divs with color borders.

๐Ÿงฉ Introduce the event object gradually by accessing event.target, then event.type, then methods like preventDefault().


๐Ÿ”ฌ Research











Use addEventListener() over inline or property-based methods.

Use event delegation for dynamic or large sets of elements.

Always clean up event listeners in SPAs or dynamically loaded content to avoid memory leaks.

Avoid anonymous functions if you plan to remove the listener later.

Use passive: true for scroll events to improve performance on mobile.

javascript code

window.addEventListener('scroll', handleScroll, { passive: true });


๐Ÿ“˜ Summary

Concept

Description

Events

Signals triggered by users or browser

Handlers

Functions that respond to events

addEventListener()

Standard method to attach handlers

Event Object

Contains data about the event

Propagation

Flow of events in the DOM tree

Delegation

Efficiently handling many child elements from a parent



๐Ÿ“š work

Build an interactive to-do list that:

Adds items

Deletes items using event delegation

Create a form with validation using event listeners and preventDefault().


Challenge











Create a mini calculator using buttons. Use event listeners for button clicks and keyboard support.


No comments:

Post a Comment

Javascript Module 34

  Javascript Module 34 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test A...