JavaScript for Programmers - Events

By Paul Deitel

Common Programming Error 1.1

Putting quotes around the function name when registering it using the inline model would assign a string to the onclick property of the node—a string cannot be called.

Common Programming Error 1.2

Putting parentheses after the function name when registering it using the inline model would call the function immediately and assign its return value to the onclick property.

Once the event handler is registered in line 28, the div in line 39 has the same behavior as the div in lines 35–36, because handleEvent (lines 19–22) is set to handle the onclick event for both divs. When either div is clicked, an alert will display "The event was successfully handled."

The traditional model allows us to register event handlers in JavaScript code. This has important implications for what we can do with JavaScript events. For example, traditional event-handler registration allows us to assign event handlers to many elements quickly and easily using repetition statements, instead of adding an inline event handler to each XHTML element. In the remaining examples in this chapter, we use both the inline and traditional registration models depending on which is more convenient.

Event onload

The onload event fires whenever an element finishes loading successfully (i.e., all its children are loaded). Frequently, this event is used in the body element to initiate a script after the page loads in the client’s browser. Figure 11.2 uses the onload event for this purpose. The script called by the onload event updates a timer that indicates how many seconds have elapsed since the document was loaded.

   1   <?xml version = "1.0" encoding = "utf-8"?>
   2   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4
   5   <!-- Fig. 11.2: onload.html -->
   6   <!-- Demonstrating the onload event. -->
   7   <html xmlns = "http://www.w3.org/1999/xhtml">
   8      <head>
   9         <title>onload Event</title>
  10         <script type = "text/javascript">
  11            <!--
  12            var seconds = 0;
  13
  14            // called when the page loads to begin the timer
  15            function startTimer()
  16            {
  17               // 1000 milliseconds = 1 second
  18               window.setInterval( "updateTime()", 1000 );
  19            } // end function startTimer
  20
  21         // called every 1000 ms to update the timer
  22         function updateTime()
  23         {
  24            ++seconds;
  25            document.getElementById( "soFar" ).innerHTML = seconds;
  26         } // end function updateTime
  27         // -->
  28         </script>
  29      </head>
  30      <body onload = "startTimer()">
  31         <p>Seconds you have spent viewing this page so far:
  32         <strong id = "soFar">0</strong></p>
  33      </body>
  34   </html>

Demonstrating the onload event



Click here for larger image

Our use of the onload event occurs in line 30. After the body section loads, the browser triggers the onload event. This calls function startTimer (lines 15–19), which in turn uses method window.setInterval to specify that function updateTime (lines 22–26) should be called every 1000 milliseconds. The updateTime function increments variable seconds and updates the counter on the page.

Note that we could not have created this program without the onload event, because elements in the XHTML page cannot be accessed until the page has loaded. If a script in the head attempts to get a DOM node for an XHTML element in the body, getElementById returns null because the body has not yet loaded. Other uses of the onload event include opening a pop-up window once a page has loaded and triggering a script when an image or Java applet loads.

Common Programming Error 1.3

Trying to get an element in a page before the page has loaded is a common error. Avoid this by putting your script in a function using the onload event to call the function.

Event onmousemove, the event Object and this

This section introduces the onmousemove event, which fires repeatedly whenever the user moves the mouse over the web page. We also discuss the event object and the keyword this, which permit more advanced event-handling capabilities. Figure 11.3 uses onmousemove and this to create a simple drawing program that allows the user to draw inside a box in red or blue by holding down the Shift or Ctrl keys.

   1   <?xml version = "1.0" encoding = "utf-8"?>
   2   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4
   5   <!-- Fig. 11.3: draw.html -->
   6   <!-- A simple drawing program. -->
   7   <html xmlns = "http://www.w3.org/1999/xhtml">
   8      <head>
   9         <title>Simple Drawing Program</title>
  10         <style type = "text/css">
  11            #canvas { width: 400px;
  12                      border: 1px solid #999999;
  13                      border-collapse: collapse }
  14            td      { width: 4px;
  15                      height: 4px }
  16            th.key  { font-family: arial, helvetica, sans-serif;
  17                      font-size: 12px;
  18                      border-bottom: 1px solid #999999 }
  19         </style>
  20         <script type = "text/javascript">
  21            <!--
  22            //initialization function to insert cells into the table
  23            function createCanvas ()
  24            {
  25               var side = 100;
  26               var tbody = document.getElementById( "tablebody" );
  27
  28               for ( var i = 0; i < side; i++ )
  29               {
  30                  var row = document.createElement( "tr" );
  31
  32                  for ( var j = 0; j < side; j++ )
  33                  {
  34                     var cell = document.createElement( "td" );
  35                     cell.onmousemove = processMouseMove;
  36                     row.appendChild( cell );
  37                  } // end for
  38
  39                  tbody.appendChild( row );
  40               } // end for
  41            } // end function createCanvas
  42
  43            // processes the onmousemove event
  44            function processMouseMove( e )
  45            {
  46               // get the event object from IE
  47               if ( !e )
  48                  var e = window.event;
  49
  50               // turn the cell blue if the Ctrl key is pressed
  51               if ( e.ctrlKey )
  52                  this.style.backgroundColor = "blue";
  53
  54               // turn the cell red if the Shift key is pressed
  55               if ( e.shiftKey )
  56                  this.style.backgroundColor = "red";
  57            } // end function processMouseMove
  58            // -->
  59         </script>
  60      </head>
  61      <body onload = "createCanvas()">
  62         <table id = "canvas" class = "canvas"><tbody id = "tablebody">
  63         <tr><th class = "key" colspan = "100">Hold <tt>ctrl</tt>
  64            to draw blue. Hold  <tt>shift</tt> to draw red.</th></tr>
  65         </tbody></table>
  66      </body>
  67   </html>

Simple drawing program



Click here for larger image



Click here for larger image



Click here for larger image

The XHTML body has a table with a tbody containing one row that gives the user instructions on how to use the program. The body’s onload attribute (line 61) calls function createCanvas, which initializes the program by filling in the table.

The createCanvas function (lines 23–41) fills in the table with a grid of cells. The CSS rule in lines 14–15 sets the width and height of every td element to 4px. Line 11 dictates that the table is 400px wide. Line 13 uses the border-collapse CSS property to eliminate space between the table cells.

Line 25 defines variable side, which determines the number of cells in each row and the number of rows created by the nested for statements in lines 28–40. We set side to 100 in order to fill the table with 10,000 4px cells. Line 26 stores the tbody element so that we can append rows to it as they are generated.




Page 2 of 3

Previous Page
1 2 3
Next Page

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date