Unbinding Events with off()
In this page:
Remove a Handler
Calling off() on an element detaches a previously attached handler so it stops responding to that event. It's the standard cleanup method for undoing whatever on() previously set up.
Example: Remove a Handler
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
function handler() { console.log("Clicked"); }
$("#btn").on("click", handler);
$("#btn").off("click", handler);
</script>
</body>
</html>
Remove All Click Handlers
Calling off(click) with just an event name removes every click handler currently attached to the selected elements, regardless of which function each one was.
Example: Remove All Click Handlers
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
$("#btn").on("click", function() { console.log("Handler A"); });
$("#btn").on("click", function() { console.log("Handler B"); });
$("#btn").off("click");
</script>
</body>
</html>
Remove One Named Handler
Passing the same function reference used in on() as off()'s second argument removes only that specific handler, leaving any other click handlers on the same element untouched.
Example: Remove One Named Handler
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
function handlerA() { console.log("A"); }
function handlerB() { console.log("B"); }
$("#btn").on("click", handlerA);
$("#btn").on("click", handlerB);
$("#btn").off("click", handlerA);
</script>
</body>
</html>
Remove Delegated Handler
When the original handler was delegated with a selector, off() needs that same selector passed as its second argument to correctly remove the delegated handler rather than leaving it attached.
Example: Remove Delegated Handler
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<ul id="list"><li>Item</li></ul>
<script>
function handler() { console.log("Item clicked"); }
$("#list").on("click", "li", handler);
$("#list").off("click", "li", handler);
</script>
</body>
</html>
Use Namespaces
Namespacing an event, like on('click.myPlugin', fn), lets you later call off('.myPlugin') to remove every handler under that namespace at once, without accidentally removing unrelated click handlers elsewhere in the code.
Example: Use Namespaces
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Click</button>
<script>
$("#btn").on("click.myPlugin", function() { console.log("Namespaced handler"); });
$("#btn").on("click", function() { console.log("Regular handler"); });
$("#btn").off(".myPlugin");
</script>
</body>
</html>
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: