Q:

How to Remove an Event Handler in jQuery

0

How to Remove an Event Handler in jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery off() Method

You can simply use the jQuery off() method to remove the event handlers that were attached with on(). Don't use the unbind() method, it has been deprecated since jQuery 3.0.

If you try out the following example, you'll find the event handler function sayHello() is not executing for the button element having the id btnOff:

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Remove Event Handler</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
function sayHello(){
    alert("Hello, World!");
}
$(document).ready(function(){
    // Attach an event handler function to click event
    $("#btnOn, #btnOff").on("click", sayHello);
 
    // Removes the click event handler from second button
    $("#btnOff").off("click");
});
</script>
</head>
<body>
    <button type="button" id="btnOn">Click On</button>
    <button type="button" id="btnOff">Click Off</button>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the ID of an Element using jQuery... >>
<< How to Check If Object is an Array in JavaScript...