jQuery interview question · Most asked
What is event delegation, and why is it useful?
Summary
Event delegation attaches one handler to a parent element and lets events from children bubble up to it; jQuery's .on(event, selector, handler) runs the handler only when the event came from an element matching the selector. It works for elements added later and uses far fewer handlers than binding to every child.
Longer Answer
// Works for rows added after this line runs, with a single handler
$("#orders").on("click", ".delete-order", function (e) {
e.preventDefault();
const id = $(this).data("id");
deleteOrder(id);
});
Inside the handler, this is the matched child element, not the parent. Delegate to the closest stable container rather than document (bubbling all the way up costs time on every event and makes behaviour hard to trace). Events that do not bubble (such as focus; use focusin) need care.
Key Points
- One handler on a parent.
- Works for future elements.
this= matched child.- Delegate to the nearest stable container.
Deep dive: Code Clinic: review a jQuery shopping cart script
More most-asked jQuery questions
- How do you make AJAX requests with jQuery?
- What is the difference between .html() and .text(), and why does it matter for security?
- What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?
- How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
- What is the difference between .attr() and .prop()?
- What are jQuery Deferreds, and how do you wait for several requests?
- What is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- What is jQuery, and is it still relevant today?