Events are actions that occur in the browser, like clicking a button, typing in input, or moving the mouse.
JavaScript can respond to these events using event handlers.
Explain the difference between an inline event handler (like onclick="...") and addEventListener().
Write a brief code example showing the preferred method.
Inline handlers mix JavaScript with HTML (which is bad for separation of concerns) and can only assign one function per event type. addEventListener() keeps JS separate and allows multiple listeners for the exact same event on a single element.
Assume you have a link selected as const link = document.querySelector('a');.
Add a click event listener to it.
Use the appropriate event method to prevent the link from navigating.
Log a message to the console confirming navigation was prevented.
You can call the preventDefault() method on the event object passed to your event listener.
const link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault(); // Stops the link from navigating
document.write('Navigation prevented!');
});
Medium
Q4: Stop event bubbling.
Explain what event bubbling is in the DOM.
Given a click event listener on an element with ID child, write the code to stop the event from bubbling up to its parent elements.
Event bubbling is the phase where an event triggers on the deepest target element and then propagates (bubbles) up to its ancestors. You can stop it using event.stopPropagation().
const childDiv = document.getElementById('child');
childDiv.addEventListener('click', function(event) {
event.stopPropagation(); // Stops the event from reaching parent elements
document.write('Child clicked, bubbling stopped.');
});
Hard
Q5: Implement event delegation.
Explain what event delegation is.
Write an example attaching a single click listener to a parent <ul> (ID: myList).
Inside the listener, check if the clicked target is an <li> element.
Log the text content of the clicked <li>.
Event delegation is a pattern where you attach a single event listener to a parent element to handle events for its children (even dynamically added ones), taking advantage of event bubbling.
const list = document.getElementById('myList');
list.addEventListener('click', function(event) {
// Check if the clicked element is an LI
if (event.target.tagName === 'LI') {
document.write('List item clicked:', event.target.textContent);
}
});