Executing JavaScript with Event Handlers


<body onload="showText();"> 

The third way to execute JavaScript code (the first two ones being <script> elements and javascript: pseudo URLs) is via en event handler. Most HTML elements support a few events; for instance, the <body> tag supports the load element. Using the on prefix, code can be attached to this event (more options are covered in Chapter 6, "OOP and Events"). Therefore, the following code runs the showText() function after the document has been fully loaded (with respect to the HTML markup of the page, not images or other external data):

Using a JavaScript Event Handler (event.html)

<html> <head> <title>JavaScript</title> <script language="JavaScript"   type="text/javascript">   function showText() {     window.alert("Welcome to JavaScript!");   } </script> </head> <body onload="showText();"> </body> </html> 

Warning

It is a common misconception that the javascript: URL prefix must be used with event handlers, in the following fashion:

<body onload="javascript:showText();"> 


However, this is completely boguswhat else if not JavaScript code could be the value of an event handler attribute? Therefore, omit the javascript: and just provide the code to be executed when the associated event is fired.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net