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 Event Targets

You can set up just a single event handler to handle a type of event for many different elements. For example, you may have many images in a page and want to write a click event handler for them all, saving you the need to duplicate a lot of code.

To do that, you'll need to determine from the event object the page element in which the event occurred, and you can do that with the target property of the event object.

The target property contains an object corresponding to the page element that was the target of the event. So, for example, if an image was clicked, the event object passed to its click event handler will contain an object corresponding to the image.

In this example, we'll use the event object's target property to recover and display the ID value of an image that the user clicked.

To get the event target:

  1. Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example target.html from the code for the book here.
  2. Enter the code to add the jQuery library and an <img> element to the page, binding the image's click event to a JavaScript function (Script 4.19).

    Script 4.19. Binding an image's click event.

    <html>
      <head>
        <title>Getting event target</title>
        <script
          src="https://code.jquery.com/jquery-
          latest.js">
        </script>
    
        <script>
          $(function( ){
            $('#figure1').bind('click',
            clicker);
          });
        </script>
      </head>
    
      <body>
        <h1>Getting event target</h1>
        <h1>Click the flower...</h1>
        <img id="figure1" src="Image1.jpg"/>
      </body>
    </html>
    
  3. Add the code to display the ID value of the clicked image (Script 4.20).

    Script 4.20. Displaying the event target's ID.

    <html>
      <head>
        <title>Getting event target</title>
        <script
          src="https://code.jquery.com/jquery-
          latest.js">
        </script>
    
        <script>
          $(function( ){
            $('#figure1').bind('click',
    
            clicker);
          });
    
          function clicker(event)
          {
            $('#p1').text(
            "ID of target element: "
            + event.target.id);
          }
        </script>
      </head>
    
      <body>
        <h1>Getting event target</h1>
        <h1>Click the flower...</h1>
        <img id="figure1" 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, displaying its ID value (Figure 4.10).
    Figure 4.10

    Figure 4.10Getting an element’s ID.

  • + Share This
  • 🔖 Save To Your Account