- 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
Calling Event Handlers Only Once
You can use jQuery to bind an event to an event handler that you want to run only once. This capability is useful if you have an initialization process that needs to be executed only once. For example, you may want to initialize an online database—a process that needs to be done only one time.
To bind events to an event handler so that the event handler is run only once, you use the one( ) function:
.one('click',function(event) {...
Let's put this function to work.
To call an event handler only once:
- Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example one.html from the code for the book here.
- Enter the code to add the jQuery library and an <img> element to the page (Script 4.7).
Script 4.7. Adding an <img> element.
<html> <head> <title>Allowing event handlers to be called only once</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> </head> <body> <h1>Allowing event handlers to be called only once</h1> <h1>Click the flower...</h1> <img id="target" src="Image1.jpg"/> </body> </html>
- Add the code to connect the image's click event to an event handler function that will be executed only once (Script 4.8).
Script 4.8. Executing an event handler only once.
<html> <head> <title>Allowing event handlers to be called only once</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target') .one('click',function(event) { alert('Hello!'); }); }); </script> </head> <body> <h1>Allowing event handlers to be called only once</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.4).
Figure 4.4 Using an event binding only once.
- Click the image, displaying an alert box.
- Click the image again; now no alert box appears.