Open In App

How does jquery .off() work ?

In this article, we are going to learn about the .off() method in jquery. JQuery is a lightweight and fast javascript library used to simplify the javascript code. It is faster than javascript because the same task can be performed faster by using JQuery.

.off() method: The task of the .off() method is to remove an event handler from the programme. It is a built-in method in JQuery and its main purpose is to remove the event handler which is attached to the HTML element by the on() method.



Syntax:

$( selector ).off( event, selector, function( eventObj ), map);

Where



Working: The .off() method in JQuery is used to remove the event handler which is connected to the HTML element by the on() method. Let us understand with the help of an example, Suppose there are various events that are attached by the on click() method and if we passed the click method in the off() method then all the click methods will be removed from the webpage. 

Note: **(double asterisk) in off() method is used to remove all delegated events from an 
element withoutremoving non-delegated events.
 

Example:




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="utf-8" />
    <title>jQuery off() method</title>
 
    <script src=
    </script>
 
    <style>
        body {
            text-align: center;
        }
    </style>
 
    <script>
        $(document).ready(function () {
            $("h2").on("click", function () {
                $(this).css("background-color", "green");
            });
            $("button").click(function () {
                $("h2").off("click");
            });
        });
    </script>
</head>
 
<body>
    <h2>
        GeeksForGeeks(click event is active).
        Click on GeeksForGeeks to see the
        effect of click event.
    </h2>
 
    <button>
        click here to remove the click event.
    </button>
     
    <h2>
        GeeksForGeeks(This is the same element as above).
        Click on the GeeksForGeeks to see the effect of
        off method.
    </h2>
</body>
 
</html>

Output:

Explanation: From the above output, you can observe that after clicking on the button ‘click event’ will be removed from the web page. Basically, the work of .off() is to remove the click event from the web page.


Article Tags :