- 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 the Event Type
You can connect a single event handler to many different types of events. For example, you may want to centralize your event handling for clicks and double-clicks in one function.
How then can you determine what type of event actually occurred: a click or a double-click?
You can use the event object's type property. That property stores the name of the event in human language. The possibilities are blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and error.
Let's take a look at an event and determine its type in an example.
To get an event’s type:
- Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example type.html from the code for the book here.
- Enter the code to add the jQuery library to the page and connect a function named clicker( ) to an <img> element (Script 4.13).
Script 4.13. Adding an <img> element and binding its click event.
<html> <head> <title>Getting event type</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target').bind('click', clicker); }); </script> </head> <body> <h1>Getting event type</h1> <h1>Click the flower...</h1> <img id="target" src="Image1.jpg"/> </body> </html>
- Add the code to display the event type in a <p> element when the image is clicked (Script 4.14).
Script 4.14. Displaying the event type.
<html> <head> <title>Getting event type</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target').bind('click', clicker); }); function clicker(event) { $('#p1').text('Event type: ' + event.type); } </script> </head> <body> <h1>Getting event type</h1> <h1>Click the flower...</h1> <img id="target" src="Image1.jpg"/> <p id="p1"></p> </body> </html>
- Save the file.
- Navigate to the file in your browser.
- Click the image, which makes the <p> element display text indicating that a click event occurred (Figure 4.7).
Figure 4.7 Catching a click event.