jQuery interview question · Most asked
A jQuery click handler fires two or three times per click. What is the likely cause, and how do you fix it?
Summary
The handler was bound more than once: typically inside a function that runs on every AJAX refresh or page update, or on elements that were re-rendered while old handlers stayed attached to a parent. Each binding adds another handler.
Longer Answer
Fixes: bind once with event delegation on a stable container, outside the refresh function; if a handler must be re-bound, remove it first with a namespace (.off("click.cart").on("click.cart", ...)); use .one() for genuinely single-use handlers. Debug by inspecting the element's listeners in browser DevTools (Event Listeners panel) or $._data(element, "events") in older versions.
Key Points
- Handlers bound repeatedly.
- Delegate once on a stable container.
- Namespaced .off before .on.
- Inspect listeners in DevTools.
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 event delegation, and why is it useful?
- 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 is the difference between preventDefault(), stopPropagation() and returning false in a jQuery handler?
- What is jQuery, and is it still relevant today?