- 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 an Event Handler to an Event
Event handling in jQuery begins by connecting an event, such as a mouse click, to an event handler. Then when the event occurs, the event handler will be called, and the code in the event handler will be executed.
You bind a page element's event to an event handler using the bind( ) function. For example, if a page contains an image and you want to bind one of the image's events to an event handler, you would execute code like this:
$("img").bind(event, data, handler)
Here, event is a string holding the type of event. The possible values 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.
The data parameter holds optional data you want passed to the event handler as the data property of the event object (you can omit this parameter), and handler is the event handler function.
Here, we'll see how to bind the click event of an image to an event handler that displays an alert box.
To bind an event:
- Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example bind.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.1).
Script 4.1. Adding an <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 the image's click event to an event handler function that displays an alert box (Script 4.2).
Script 4.2. Binding an image's click event.
<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!'); }); }); </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 to display an alert box (Figure 4.1).
Figure 4.1 Triggering an image's click event.