How to Remove an Event Handler using jQuery ?
In this tutorial, we will discuss how we can remove an event handler using jQuery. There are three methods to solve this problem which are discussed below:
Table of Content
- Using unbind() method
- Using off() Method
Using unbind() method
It is an inbuilt method in jQuery that is used to remove selected event handlers. It accepts the optional parameters as the name of the event, function, and the object that has to be removed.
Syntax:
$(selector).unbind(event, function, eventObj)
Example 1: The below example explains the use of the unbind() method to remove the event handler.
html
<!DOCTYPE html> < html > < head > < title > jQuery | How to remove an event handler? </ title > < script src = "https://code.jquery.com/jquery-2.2.4.min.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < h3 > Remove an event handler using unbind method </ h3 > < h4 > The value will not get updated once you click the button. </ h4 > < input type = "text" id = "myInput" /> < p class = "result" ></ p > < button > Remove Event </ button > < script > $(document).ready(function() { $("#myInput").change(function() { $('.result').text($(this).val()); }); $("button").click(function() { $("#myInput").unbind(); }); }); </ script > </ body > </ html > |
Output:
Using off() Method
It is used to remove event handlers attached with the on() method. It can be used with the optional parameters like event name, function, selector, and map.
Syntax:
$(selector).off(event, selector, function(eventObj), map)
Example 2: The below code example illustrates the use of the off() method to remove the event handler.
html
<!DOCTYPE html> < html > < head > < title > jQuery | How to remove an event handler? </ title > < script src = "https://code.jquery.com/jquery-2.2.4.min.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < h3 > Remove an event handler using unbind method </ h3 > < h4 > The value will not get updated once you click the button. </ h4 > < input type = "text" id = "myInput" /> < p class = "result" ></ p > < button > Remove Event </ button > < script > $(document).ready(function() { $("#myInput").change(function() { $('.result').text($(this).val()); }); $("button").click(function() { $("#myInput").off(); }); }); </ script > </ body > </ html > |
Output: