Event Propagation in JavaScript (For BCA 6th Semester)
Event propagation is a concept in JavaScript that describes how events travel (propagate) through
the elements in a web page when an event (like a button click) occurs. It helps in controlling how the
event should behave and which element should respond to it.
What is Event Propagation?
- When you click or interact with a web page element, the event doesn't just affect that element.
- The event moves through the HTML structure in a specific way.
- Event Propagation controls how events move from one element to another.
Types of Event Propagation Methods:
Event Propagation works in three phases:
1. Capturing Phase (Event Capturing)
- The event starts from the top of the web page (root) and moves downward to the target element.
- Think of it like water flowing from a tree's root to its leaves.
- Used rarely, but useful for specific needs.
2. Target Phase
- The event reaches the exact element where the interaction happened.
- Example: Clicking on a button will trigger the button's click event directly.
3. Bubbling Phase (Event Bubbling)
- After the event is handled at the target, it moves upward from the target element to the root.
- Think of it like bubbles in water rising from the bottom to the top.
- It is commonly used for tasks like form validation or menu handling.
Real-Life Example of Event Propagation:
To understand event propagation, think of a school function scenario:
1. Capturing Phase (Event Capturing)
- The Principal hears about the problem first and informs the Class Teacher to handle it.
- This is like the event starting from the topmost authority and moving downward.
2. Target Phase
- The Class Teacher directly approaches the concerned Student (the actual source of the issue).
- This represents the phase where the event reaches the target element.
3. Bubbling Phase (Event Bubbling)
- After resolving the issue, the Student informs the Class Teacher about it.
- The Class Teacher then reports back to the Principal.
- This is like the event moving upward, just like bubbles in water rising from bottom to top.
Example in Code:
<!DOCTYPE html>
<html>
<head>
<script>
function showAlert(message) {
alert(message);
</script>
</head>
<body>
<div onclick="showAlert('Div clicked!')" style="padding: 50px; background-color: lightblue;">
Div
<button onclick="showAlert('Button clicked!')" style="padding: 20px;">Click Me</button>
</div>
</body>
</html>
Explanation:
- Clicking on the button triggers both the button and the div's onclick event.
- The event bubbles up from the button to the div, then to the document.
- You can control this using event.stopPropagation() if you don't want the parent elements to
respond.
Conclusion:
- Event Capturing is like information flowing from principal to student.
- Target Phase is when the student directly responds.
- Event Bubbling is like the response flowing back up.
- Event Propagation is useful in handling multiple events efficiently in web applications.