- 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
Binding Multiple Event Handlers
jQuery also allows you to bind multiple event handlers to events.
For example, you could bind three different event handler functions to a page element's click event like this, where you call the bind( ) function three different times:
$('#target') .bind('click',function(event) { alert('Hello!'); }) .bind('click',function(event) { alert('Hello again!'); }) .bind('click',function(event) { alert('Hello yet again!'); });
Now when the click event occurs, the first event handler will be called, followed by the second, followed by the third.
We'll put this code to work in an example.
to bind multiple event handlers:
- Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example multiple.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.3).
Script 4.3. Adding one <img> element.
<html> <head> <title>Binding event handlers to events</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> </head> <body> <h1>Binding event handlers to events</h1> <h1>Click the flower...</h1> <img id="target" src="Image1.jpg"/> </body> </html>
- Add the code to bind three event handlers to the image's click event (Script 4.4).
Script 4.4. Binding three event handlers.
<html> <head> <title>Binding event handlers to events</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target') .bind('click',function(event) { alert('Hello!'); }) .bind('click',function(event) { alert('Hello again!'); }) .bind('click',function(event) { alert('Hello yet again!'); }); }); </script> </head> <body> <h1>Binding event handlers to events</h1> <h1>Click the flower...</h1> <img id="target" src="Image1.jpg"/> </body> </html>
- Save the file.
- Navigate to the file in your browser.
- Click the image, which will display a succession of alert boxes, one of which is shown in Figure 4.2.
Figure 4.2 An alert box.