- Event Handling in JavaScript and jQuery
- Binding an Event Handler to an Event
- Binding Multiple Event Handlers
- Binding Event Handlers Using Shortcuts
- Calling Event Handlers Only Once
- Unbinding Event Handlers
- Using the Event Object
- Getting Mouse Coordinates
- Getting the Event Type
- Capturing Keystrokes
- Capturing Hover Events
- Getting Event Targets
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:
- 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.
- 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>
- 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>
- Save the file.
- Navigate to the file in your browser (Figure 4.5).
Figure 4.5 Unbinding an event handler.
- Click the image, displaying the alert box and unbinding the click event.
- Click the image again to ensure that there's no response.