Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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

  1. 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.
  2. 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="http://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>
    
  3. 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="http://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>
    
  4. Save the file.
  5. Navigate to the file in your browser.
  6. Move the mouse over the text to see it turn to italics (Figure 4.9).
    Figure 4.9

    Figure 4.9 Italicizing text.

  • + Share This
  • 🔖 Save To Your Account