- 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
Capturing Hover Events
The jQuery library has a special function for handling mouse hover events, in which the mouse cursor rests on a page element. That function is hover( ):
hover(over, out)
You pass two functions to hover( ): the over( ) function should be called when the mouse is over a page element, and the out( ) function should be called when the mouse leaves the page element.
In this example, we'll italicize some text in a page when the mouse hovers over that text, and restore it to normal when the mouse leaves.
To capture hover events
- Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example hover.html from the code for the book here.
- Enter the code to add the jQuery library to the page and a <p> element with some text in it, binding the hover events to two JavaScript functions (Script 4.17).
Script 4.17. Binding hover events.
<html> <head> <title>Capturing hover events</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target').hover(over, out); }); </script> </head> <body> <h1>Capturing hover events</h1> <p id="target">Here is the text!</p> </body> </html>
- Add the code to italicize the text in the <p> element when the mouse hovers over it, and restore the text to normal when the mouse leaves (Script 4.18).
Script 4.18. Catching hover events.
<html> <head> <title>Capturing hover events</title> <script src="https://code.jquery.com/jquery- latest.js"> </script> <script> $(function( ){ $('#target').hover(over, out); }); function over(event) { $('#target').css("font-style", "italic"); } function out(event) { $('#target').css("font-style", "normal"); } </script> </head> <body> <h1>Capturing hover events</h1> <p id="target">Here is the text!</p> </body> </html>
- Save the file.
- Navigate to the file in your browser.
- Move the mouse over the text to see it turn to italics (Figure 4.9).
Figure 4.9 Italicizing text.