1. What is Event Propagation
The process of deciding when and in which direction event will be executed is called Event Propagation.
2. What is Event Bubbling
Like bubble events are executed from down to up.
3. Events which donot bubble
- scroll (except that a scroll event on document must bubble to the window)
- Focus
- Blur
4. event.target v/s this.tagName v/s event.currentTarget
event.target donot bubble
event.currentTarget & this bubble
target is where we clicked. this& currentTarget is where the event listener is attached to.
5. What is Event Capturing / Trickling
Event gets called from top to bottom. When clicked inside button. Div => Form => Button.
document.querySelector(".eventCaptureDiv")?.addEventListener(
"click",
() => {
alert("Div");
},
{ capture: true }
);
document.querySelector(".eventCaptureForm")?.addEventListener(
"click",
() => {
alert("Form");
},
{ capture: true }
);
document.querySelector(".eventCaptureButton")?.addEventListener(
"click",
() => {
alert("Button");
},
{ capture: true }
);
6. What is stopPropagation.
For all the event we can use event.stopPropagation() to stop both Bubbling & Capturing effect.
document.querySelector("div")?.addEventListener("click", (event) => {
event.stopPropagation();
alert("Div");
});
document.querySelector("form")?.addEventListener("click", (event) => {
event.stopPropagation();
alert("Form");
});
document.querySelector("button")?.addEventListener("click", (event) => {
event.stopPropagation();
alert("Button");
});
7. What is stopImmediatePropagation.
stopPropagation will only stop parent/child events from bubbling or capturing.
stopImmediatePropagation will stop the propagation of same element after it is called. It means if we have multiple events for a element. Once we call stopImmediatePropagation. The remaining events of that element will be also stopped.
8. What is Event Delegation
Event Delegation is the process of adding eventListener to the parent instead of adding it to multiple child elements.
document.querySelector("gridContainer")?.addEventListener("click", (event) => {
if (event.target.tagName === "SPAN" || event.target.closest("SPAN")) {
alert(event.target.textContent);
}
});
9. Run the Events in the order Form => Button => Div
document.querySelector(".eventCaptureDiv")?.addEventListener("click", () => {
alert("Div");
});
document.querySelector(".eventCaptureForm")?.addEventListener(
"click",
() => {
alert("Form");
},
{ capture: true }
);
document.querySelector(".eventCaptureButton")?.addEventListener(
"click",
() => {
alert("Button");
}
);
10. Close the modal based on outside click
document.querySelector("modal-overlay")?.addEventListener("click", (event) => {
if (event?.target.className === "modal-overlay") {
document.querySelector("modal-container").style.display = "none";
}
});