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

Calling Event Handlers Only Once

You can use jQuery to bind an event to an event handler that you want to run only once. This capability is useful if you have an initialization process that needs to be executed only once. For example, you may want to initialize an online database—a process that needs to be done only one time.

To bind events to an event handler so that the event handler is run only once, you use the one( ) function:

.one('click',function(event) {...

Let's put this function to work.

To call an event handler only once:

  1. Use a text editor (such as Microsoft WordPad) to create your Web page. We'll use the example one.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.7).

    Script 4.7. Adding an <img> element.

    <html>
      <head>
        <title>Allowing event handlers to be
          called only once</title>
        <script
          src="http://code.jquery.com/jquery-
          latest.js">
        </script>
      </head>
    
      <body>
        <h1>Allowing event handlers to be
          called only once</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 will be executed only once (Script 4.8).

    Script 4.8. Executing an event handler only once.

    <html>
      <head>
        <title>Allowing event handlers to be
          called only once</title>
        <script
          src="http://code.jquery.com/jquery-
          latest.js">
        </script>
    
        <script>
          $(function( ){
            $('#target')
              .one('click',function(event) {
                alert('Hello!');
              });
          });
        </script>
      </head>
    
      <body>
        <h1>Allowing event handlers to be
          called only once</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 (Figure 4.4).
    Figure 4.4

    Figure 4.4 Using an event binding only once.

  6. Click the image, displaying an alert box.
  7. Click the image again; now no alert box appears.
  • + Share This
  • 🔖 Save To Your Account