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

Getting the Event Type

You can connect a single event handler to many different types of events. For example, you may want to centralize your event handling for clicks and double-clicks in one function.

How then can you determine what type of event actually occurred: a click or a double-click?

You can use the event object's type property. That property stores the name of the event in human language. The possibilities 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.

Let's take a look at an event and determine its type in an example.

To get an event’s type:

  1. Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example type.html from the code for the book here.
  2. Enter the code to add the jQuery library to the page and connect a function named clicker( ) to an <img> element (Script 4.13).

    Script 4.13. Adding an <img> element and binding its click event.

    <html>
      <head>
        <title>Getting event type</title>
        <script
        src="https://code.jquery.com/jquery-
        latest.js">
        </script>
    
        <script>
          $(function( ){
          $('#target').bind('click',
             clicker);
          });
        </script>
      </head>
    
      <body>
        <h1>Getting event type</h1>
        <h1>Click the flower...</h1>
        <img id="target" src="Image1.jpg"/>
      </body>
    </html>
    
  3. Add the code to display the event type in a <p> element when the image is clicked (Script 4.14).

    Script 4.14. Displaying the event type.

    <html>
      <head>
        <title>Getting event type</title>
        <script
        src="https://code.jquery.com/jquery-
        latest.js">
        </script>
    
        <script>
          $(function( ){
          $('#target').bind('click',
             clicker);
          });
    
          function clicker(event)
          {
        $('#p1').text('Event type: '
        + event.type);
          }
        </script>
      </head>
    
      <body>
        <h1>Getting event type</h1>
        <h1>Click the flower...</h1>
        <img id="target" src="Image1.jpg"/>
        <p id="p1"></p>
      </body>
    </html>
    
  4. Save the file.
  5. Navigate to the file in your browser.
  6. Click the image, which makes the <p> element display text indicating that a click event occurred (Figure 4.7).
    Figure 4.7

    Figure 4.7 Catching a click event.

  • + Share This
  • 🔖 Save To Your Account