Open In App

jQuery | off() Method

The off() Method in jQuery is used to remove event handlers attached with the on() method. The off() method brings a lot of consistency to the API and it replace unbind(), die() and undelegate() methods.

Syntax:



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

Parameter: This method accepts four parameters as mentioned above and described below:

Example 1: This example removes the event handler.




<!DOCTYPE html>
<html>
      
<head>
    <title>
        jQuery off() method
    </title>
  
    <script src=
    </script>
      
    <!-- Script to remove event handler -->
    <script>
        $(document).ready(function() {
            $("h3").on("click", function() {
                $(this).css("background-color", "green");
            });
              
            $("button").click(function() {
                $("h3").off("click");
            });
        });
    </script>
</head>
  
<body>
        <h3>GeeksforGeeks</h3
          
        <button>
            Click to remove event handler
        </button>
</body>
  
</html>

Output:
Before Click on the element h3:

After Click on the element h3:



Example 2: This example use animate event to add animation effect one time and then remove the event handler.




<!DOCTYPE html>
<html>
      
<head>
    <title>
        jQuery off() method
    </title>
      
    <script src=
    </script>
      
    <!-- Script to animate the event -->
    <script>
        $(document).ready(function() {
            var x = 0;
              
            $("h3").click(function(event) {
                $("h3").animate({fontSize: "+=10px"
            });
              
            x++;
              
            if (x >= 1) {
                $(this).off(event);
            }
            });
        });
    </script>
</head>
  
<body style="text-align:center;">
  
    <h1>Welcome to GeeksforGeeks!.</h1
            
    <div style="background-color:green;">
        <h3>
            Geeks for Geeks. Click to increase
            the size (only one time)
        </h3>    
    </div>
</body>
  
</html>

Output :
Before Click on the heading:

After Click on the heading:


Article Tags :