- 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
Getting Event Targets
You can set up just a single event handler to handle a type of event for many different elements. For example, you may have many images in a page and want to write a click event handler for them all, saving you the need to duplicate a lot of code.
To do that, you'll need to determine from the event object the page element in which the event occurred, and you can do that with the target property of the event object.
The target property contains an object corresponding to the page element that was the target of the event. So, for example, if an image was clicked, the event object passed to its click event handler will contain an object corresponding to the image.
In this example, we'll use the event object's target property to recover and display the ID value of an image that the user clicked.
To get the event target:
- Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example target.html from the code for the book here.
- Enter the code to add the jQuery library and an <img> element to the page, binding the image's click event to a JavaScript function (Script 4.19).
Script 4.19. Binding an image's click event.
<html> <head> <title>Getting event target</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#figure1').bind('click', clicker); }); </script> </head> <body> <h1>Getting event target</h1> <h1>Click the flower...</h1> <img id="figure1" src="Image1.jpg"/> </body> </html>
- Add the code to display the ID value of the clicked image (Script 4.20).
Script 4.20. Displaying the event target's ID.
<html> <head> <title>Getting event target</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#figure1').bind('click', clicker); }); function clicker(event) { $('#p1').text( "ID of target element: " + event.target.id); } </script> </head> <body> <h1>Getting event target</h1> <h1>Click the flower...</h1> <img id="figure1" src="Image1.jpg"/> <p id="p1"></p> </body> </html>
- Save the file.
- Navigate to the file in your browser.
- Click the image, displaying its ID value (Figure 4.10).
Figure 4.10Getting an element’s ID.