![]() |
|
![]() ![]() ![]() |
|
Event Handlers
There is one last topic we need to look at before starting to build some JavaScripts: event handlers. I didn't include this in the list of JavaScript components, because events occur in the interaction between the user and page, and the event handlers are generally embedded in the HTML code rather than the scripts themselves. The idea is to define some function using a JavaScript placed in the HEAD section of the page. A command is then embedded in the page to activate this function when the user performs some action, such as clicking on a particular place. Many of the events, but not all, are related to items in an HTML form. Note that support for event handlers differs in a number of respects for Netscape and Internet Explorer. You will want to study the documentation on the Netscape and Microsoft sites before using event handlers extensively. Here is a list of events to which JavaScript functions can potentially be attached:
The general form for event handlers is: onEvent="function()" There are a couple of important exceptions to this form:
Here are some samples, showing you two ways to call the same function (the first works in IE only; the second in IE or Netscape): Click here for an important message!Click here to get another message! Code for the samples: <script language="JavaScript"> <!-- // hide this from non-JS browsers function myMessage(message) { alert(message) } // hide this from non-JS browsers --> </script> <a onclick="myMessage('This is my message.')">Click <span class="red2">here</span> for an important message!</a><br> <a href="javascript:myMessage('This is my second message!')">Click here to get another message!</a><br> Here's a more complex DHTML sample used in the contents frame to the left (adapted from a DHTML sample in Microsoft's Web Gallery): <div id="Rollover"> <table cellpadding="3"> <tr><td> <a href="contents.html"><span class="Item">Contents</span></a> </td></tr> <tr><td> <a href="js_001.html"><span class="Item">Introduction</span></a> </td></tr> </table> </div> <script> <!-- var browser=navigator.appName; var version=navigator.appVersion var ver1=version.substring(0,1) if ((browser == "Microsoft Internet Explorer") && (ver1 >= 4)) { function rollon() { if (window.event.srcElement.className == "Item") { window.event.srcElement.className = "Highlight"; } } Rollover.onmouseover = rollon; function rolloff() { if (window.event.srcElement.className == "Highlight") { window.event.srcElement.className = "Item"; } } Rollover.onmouseout = rolloff; } // --> </script> Note the check to see if the user has IE 4.0 at the beginning of the script. This is important unless the page is on an all-IE intranet, because Netscape and IE 3 will return an error on this script. Also note the special IE 4 window property .event.srcElement.className, which returns the style class used for the element (that the mouse is currently over). |
|
![]() ![]() ![]() |
|
|