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

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

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

This chapter is from the book

Binding Multiple Event Handlers

jQuery also allows you to bind multiple event handlers to events.

For example, you could bind three different event handler functions to a page element's click event like this, where you call the bind( ) function three different times:

$('#target')
  .bind('click',function(event) {
    alert('Hello!');
  })
  .bind('click',function(event) {
    alert('Hello again!');
  })
  .bind('click',function(event) {
    alert('Hello yet again!');
  });

Now when the click event occurs, the first event handler will be called, followed by the second, followed by the third.

We'll put this code to work in an example.

to bind multiple event handlers:

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

    Script 4.3. Adding one <img> element.

    <html>
      <head>
        <title>Binding event handlers to
           events</title>
        <script
          src="http://code.jquery.com/jquery-
          latest.js">
        </script>
      </head>
    
      <body>
        <h1>Binding event handlers to
           events</h1>
        <h1>Click the flower...</h1>
        <img id="target" src="Image1.jpg"/>
      </body>
    </html>
    
  3. Add the code to bind three event handlers to the image's click event (Script 4.4).

    Script 4.4. Binding three event handlers.

    <html>
      <head>
        <title>Binding event handlers to
           events</title>
        <script
          src="http://code.jquery.com/jquery-
          latest.js">
        </script>
    
        <script>
          $(function( ){
            $('#target')
              .bind('click',function(event) {
                alert('Hello!');
              })
              .bind('click',function(event) {
                alert('Hello again!');
              })
              .bind('click',function(event) {
                alert('Hello yet again!');
              });
          });
        </script>
      </head>
    
      <body>
        <h1>Binding event handlers to
           events</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, which will display a succession of alert boxes, one of which is shown in Figure 4.2.
    Figure 4.2

    Figure 4.2 An alert box.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus