The .off() Method

With the release of jQuery 1.7, the .off() method came as a replacement for the .unbind(), .die() and .undelegate() methods.

The .off() method lets us remove event handlers attached with the .on() method and takes the syntax below

				
				$(elements).off(events,descendant,handler)
				
			
jquery off
events
Required. One or more events (separated by spaces) attached to the selected element. The events can also be namespaced.
descendant
Optional. Specified descendant of selected element matching the one originally passed to .on().
handler
Optional. The function to be executed when the event is fired.

We will consider the same example from the previous lesson by attaching the click event handler to the only <p> element in the document. When the <p> element is clicked, the console logs a message.

				
				<!DOCTYPE html>
				<html lang="en">
				<head>
					<title>Title of this Page</title>	
					<script type="text/javascript" src="//code.jquery.com/jquery-latest.min.js">
					</script>
				</head>
				<body>
				    <p>This is a paragraph.</p> 

				    <script type="text/javascript">
				    	$(document).ready(function(){
							$("p").on("click", function(){
							    console.log("You clicked a paragraph.");
							});
						});
				    </script>
				</body>
				</html>
				
			

Now using the .off() method, if we append the following line of code inside $(document).ready()

				
				$("p").off("click");
				
			

or type it into the browser console, the click event from the <p> element will be removed, and the console message will not appear anymore. In fact, all event handlers attached to the <p> element in the document can be removed on execution of the following code

				
				$("p").off();
				
			

Removing Event Handler on Descendants

The .on() method's event delegation allows us to attach an event listener to an element that will trigger for all its descendants matching the selector, irrespective of their current existence in the document or in the future.

We illustrate this below by attaching the click event to the <body> element and assigning its descendant element "p" and a handler function f() as the second and third parameters of the .on() method respectively. On click of <p>, a message will be logged into the console.

					
					var f = function() {
					  console.log("You clicked a paragraph.");
					};

					$(document).ready(function(){
						$("body").on("click", "p", f);	
					});
					
				

Using the .off() method, we can remove the handler from <p> as

					
					$("body").off("click", "p", f);
					
				

If, however, instead of the function f(), we pass an anonymous function, it will fail to work.

All delegated event handlers from the <body> element can be removed using the following line of code

					
					$("body").off("click", "**");