Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Unbinding Event Handlers

You can also disconnect events from event handlers using jQuery. For example, if an option is no longer available in your application, you may want to remove the click event handler that responds to events.

You can disconnect events from event handlers using the unbind( ) function:

.unbind('click',function(event) {...

You just need to pass the unbind( ) function the name of the event you're disconnecting and the event handler to which the event is currently tied.

Let's give this function a try by disconnecting a click event from an image when the image is clicked.

To unbind an event:

  1. Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example unbind.html from the code for the book here.
  2. Enter the code to add the jQuery library and <img> elements to the page with a click event connected to a function named clicker( ) (Script 4.9).

    Script 4.9. Connecting a click event to a handler.

    <html>
      <head>
        <title>Unbinding event handlers</title>
        <script
         src="https://code.jquery.com/jquery-
         latest.js">
        </script>
    
        <script>
          $(function( ){
            $('#target').bind('click',
              clicker);
          });
        </script>
      </head>
    
      <body>
        <h1>Unbinding event handlers</h1>
        <h1>Click the flower...</h1>
        <img id="target" src="Image1.jpg"/>
      </body>
    </html>
    
  3. Add the code to display an alert box in the clicker( ) function and then disconnect the click event from the clicker( ) function (Script 4.10).

    Script 4.10. Unbinding a click event.

    <html>
      <head>
        <title>Unbinding event handlers</title>
        <script
         src="https://code.jquery.com/jquery-
         latest.js">
        </script>
    
        <script>
          $(function( ){
            $('#target').bind('click',
              clicker);
          });
    
          function clicker(event)
          {
            alert(Click event unbound');
            $('#target').unbind('click', \
             clicker);
          }
        </script>
      </head>
    
      <body>
        <h1>Unbinding event handlers</h1>
        <h1>Click the flower...</h1>
        <img id="target" src="Image1.jpg"/>
      </body>
    </html>
    
  4. Save the file.
  5. Navigate to the file in your browser (Figure 4.5).
    Figure 4.5

    Figure 4.5 Unbinding an event handler.

  6. Click the image, displaying the alert box and unbinding the click event.
  7. Click the image again to ensure that there's no response.
  • + Share This
  • 🔖 Save To Your Account