Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How does jquery .off() work ?

  • Last Updated : 14 Jan, 2022

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

  • event: It specifies the event from the selected elements.
  • selector: It specifies the element whose attached event handler is to be removed.
  • function: It specifies the name of the function which is to be run to handle the event and it is an optional parameter.
  • map: It specifies an event map which is a key-value pair, where key specifies the events and values specifies the respective handler function.

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:

HTML




<!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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!