jQuery interview question · Most asked
How do you bind and unbind events in modern jQuery? What happened to bind, live and delegate?
Summary
Use .on() to attach handlers and .off() to remove them, and .one() for handlers that should run once. .bind(), .unbind(), .delegate() and .undelegate() were deprecated in jQuery 3.0, and .live() was removed in 1.9; .on() replaces all of them, including delegated handling.
Longer Answer
$("#menu").on("click", ".item", onItemClick); // delegated
$(window).on("resize.layout", relayout); // namespaced
$(window).off("resize.layout"); // remove only ours
Shorthands such as .click(fn) still work but are deprecated in favour of .on("click", fn) in recent versions. To remove a specific handler, pass the same function reference to .off(), or use a namespace.
Key Points
.on()/.off()/.one().- bind/delegate deprecated; live removed.
- Same function reference or namespace to remove.
- Shorthand methods deprecated.
More most-asked jQuery questions
- How do you make AJAX requests with jQuery?
- What is event delegation, and why is it useful?
- What is the difference between $(document).ready(), $(fn), DOMContentLoaded and window.onload?
- What is the difference between .html() and .text(), and why does it matter for security?
- 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?