- 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 Event Handlers Using Shortcuts
You don't need to bind an event handler to a page event using the bind( ) function like this:
.bind('click',function(event) {...
Instead, you can use a shortcut: you can use the event name as the binding function itself. Here's how to bind the click event, for example:
.click(function(event) {...
Note the difference; you don't pass the name of the event to bind here, just the event handler function.
Here are the possible shortcut functions: blur( ), focus( ), load( ), resize( ), scroll( ), unload( ), beforeunload( ), click( ), dblclick( ), mousedown( ), mouseup( ), mousemove( ), mouseover( ), mouseout( ), mouseenter( ), mouseleave( ), change( ), select( ), submit( ), keydown( ), keypress( ), keyup( ), and error( ).
We'll put this code to work in an example; we'll bind the click event of an image to a handler function using the click( ) function.
To bind an event using a shortcut:
- Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example click.html from the code for the book here.
- Enter the code to add the jQuery library and some <img> elements to the page (Script 4.5).
Script 4.5. Adding an <img> element as an event source.
<html> <head> <title>Binding event handlers using shortcuts</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> </head> <body> <h1>Binding event handlers using shortcuts</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 displays an alert box using the click( ) shortcut (Script 4.6).
Script 4.6. Using a click() shortcut.
<html> <head> <title>Binding event handlers using shortcuts</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target') .click(function(event) { alert('Hello!'); }); }); </script> </head> <body> <h1>Binding event handlers using shortcuts</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, displaying the alert box (Figure 4.3).
Figure 4.3 Using an event binding shortcut function.