Best way to remove an event handler in jQuery

Learn, how can we remove an event handler from an element using jQuery?
Submitted by Pratishtha Saxena, on August 23, 2022

First of all, let's see what is an event handler?

An event handler is a function or a task that is attached to an element, which is generally triggered onclick of a button. Like when a button is clicked, the function attached to it gets triggered and does its job, i.e., implements the code inside it. There are many event handlers: click(), blur(), bind(), hover(), keyup(), keydown(), etc.

But sometimes there is a need to remove the event handler attached to a specific element in jQuery. For the same, we will be going to use the off() method of jQuery which will help us to remove the event handler easily.

Note: unbind() method can also be used but now we should prefer the off() method because unbind() has been deprecated since the jQuery 3.0 version.

Syntax:

$('selector').off();

Hence, it is very simple to use. When you want any element to stop triggering the event handler attached to it, this will just switch it off.

Example to remove an event handler in jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>Remove An Event Handler</h2>
    <p id="myPara">This is a CSS background-color property.</p>
    <button type="button" id="button1">Click Here</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        function RunThis(){
            $('#myPara').css("background-color", "yellow");
        };  	
        $('#button1').click(RunThis)
        $('#button1').off();
    });    
  </script>
</html>

Output:

See the script code, on the button1's click event, we are calling RunThis() function which is setting the background-color of the <p> element "yellow" but just after, we are removing the event using the statement $('#button1').off();. Thus, button1's click event won't work.

Example 1: Remove an event handler in jQuery

Now to test, how does it work? Just comment the statement $('#button1').off(); and the perform the click event on button1. The background color will be set.

Example 2: Remove an event handler in jQuery






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.