How to remove event handlers using jQuery?

jQueryWeb DevelopmentFront End Technology

Once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.

jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows.

The following is the description of the parameters −

  • eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
  • handler − If provided, identifies the specific listener that's to be removed.

Example

You can try to run the following code to learn how to remove event handlers using jQuery −

Live Demo

<html>

   <head>
      <title>jQuery Unbind</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {

            function aClick() {
               $("div").show().fadeOut("slow");
            }
               
            $("#bind").click(function () {
               $("#theone").click(aClick).text("Can Click!");
            });
               
            $("#unbind").click(function () {
               $("#theone").unbind('click', aClick).text("Does nothing...");
            });
               
         });
      </script>
       
      <style>
         button {
            margin:5px;
         }
         button#theone {
             color:red;
             background:yellow;
         }
      </style>
   </head>
   
   <body>
   
      <button id = "theone">Does nothing...</button>
      <button id = "bind">Bind Click</button>
      <button id = "unbind">Unbind Click</button>
       
      <div style = "display:none;">Click!</div>
       
   </body>
   
</html>
raja
Published on 19-Dec-2017 17:46:28
Advertisements