|
To access the contents, click the chapter and section titles.
Platinum Edition Using HTML 4, XML, and Java 1.2
Listing 18.2 CallJS.htmCalling a JavaScript Function with the Click of a Button or Hypertext Link <HTML> <HEAD> <SCRIPT LANGUAGE=JavaScript> <!-- Hide this script from incompatible Web browsers! --> function pressed() { alert(I said Dont Press Me!); } // Hide this script from incompatible Web browsers! --> </SCRIPT> <TITLE>JavaScripts Attached to HTML Elements...</TITLE> </HEAD> <BODY BGCOLOR=#FFFFFF> <FORM NAME=Form1"> <H1>JavaScripts Attached to HTML Elements...</H1> <HR> <DL> <DT>Attach Javascript user function to button with onClick event...</DT> <DD><INPUT TYPE=button NAME=Button1" VALUE=Dont Press Me! onClick=pressed()></DD> <DT>&nbsp</DT> <DT>Attach Javascript system function to button with onClick event...</DT> <DD><INPUT TYPE=button NAME=Button2" VALUE=Dont Press Me! onClick=alert(I said Don\t Press Me!)></DD> </FORM> <DT>Attach Javascript user function to hypertext link with ⇒javascript: url...</DT> <DD><A HREF=javascript:pressed()>Dont Press Me!</A></DD> </DL> <HR> <A HREF=mailto:odonnj@rpi.edu><EM>Jim ODonnell</EM></A> </BODY> </HTML>
Three ways to call a JavaScript function from an HTML element are shown in Listing 18.2. The first attaches a user function call to the onClick event of an HTML forms element. The second way shows that you can directly call built-in JavaScript functions using the onClick event. This works particularly well when you are trying to do something simple. Finally, you can use the javascript: URL protocol to attach a JavaScript function call to a hypertext link. In the example shown in Listing 18.2, clicking either button or the hypertext link pops up the alert box shown in Figure 18.2. JavaScript also provides you with an alternative way to attach functions to objects and their events. For simple actions, you can attach the JavaScript directly to the attribute of the HTML form element. This listing produces the output shown in Figure 18.2. Sometimes you have code that should not be evaluated or executed until after all the pages HTML has been parsed and displayed. An example would be a function to print out all the URLs referenced in the page. If this function is evaluated before all the HTML on the page has been loaded, it misses some URLs. Therefore, the call to the function should come at the pages end. You can define the function itself anywhere in the HTML document; it is the function call that you should put at the end of the page.
|
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement. |