Learn advanced event handling techniques and event propagation.
Example of using event listeners and exploring event propagation:
// Adding a basic click event listener
document.getElementById("btn").addEventListener("click", function () {
alert("Button clicked!");
});
// Event propagation: Bubbling
document.getElementById("child").addEventListener("click", function () {
console.log("Child clicked");
});
document.getElementById("parent").addEventListener("click", function () {
console.log("Parent clicked");
});
// Using options
document.getElementById("btn").addEventListener("click", function () {
console.log("This will run only once.");
}, { once: true });
This code demonstrates:
once
to limit listener execution.Event listeners in JavaScript enable the detection and response to user interactions and other events on the page. You can use the addEventListener()
method to attach handlers for different types of events such as click
, keydown
, mouseover
, and more.
Key concepts include:
once
(run only once), capture
(use capture phase), and passive
(improves performance).removeEventListener()
to detach a previously attached event listener.Q1: Which method is used to attach an event handler to an element?
Answer: C. addEventListener
Q2: What is event bubbling?
Answer: B. Event flows from child to parent
Q3: What does the once
option do in addEventListener
?
Answer: C. Ensures the handler runs only one time
Q4: Which method is used to remove a previously attached event listener?
Answer: C. removeEventListener