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

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:

  1. 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.
  2. 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="http://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>
    
  3. 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="http://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>
    
  4. Save the file.
  5. Navigate to the file in your browser.
  6. Click the image, displaying the alert box (Figure 4.3).
    Figure 4.3

    Figure 4.3 Using an event binding shortcut function.

  • + Share This
  • 🔖 Save To Your Account