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)
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. |