The following example shows a simple JavaScript program, or "script," embedded in a Web page. When loaded into a JavaScript-enabled browser, it produces the output shown in Notice that the <script> and </script> tags are used to embed client-side JavaScript code within an HTML file.
<html> <body> <script language="JavaScript">; document.write("<h2>Table of Factorials</h2>"); for(i = 1, fact = 1; i < 10; i++, fact *= i) { document.write(i + "! = " + fact); document.write("<br>"); } </script> </body> </html>
As the example shows, the document.write() method can be used, in client-side JavaScript, to dynamically output HTML text that will be parsed and displayed by the Web browser. Besides allowing control over the appearance and content of Web pages, JavaScript provides control over the behavior of the browser, and also over the behavior and content of HTML forms that appear in a Web page.
The use of event handlers can also be powerful. Event handlers specify code to be executed when a particular event occurs. The HTML fragment shown below produces a simple form with a button. The onClick attribute of the <input> button type (an HTML extension added by Netscape specifically for client-side JavaScript) defines an event handler that will be executed when the user clicks the button. As shown in the alert() function called by the event handler causes a dialog box to be displayed.
<form> <input type="button" value="Click here" onClick="alert('You clicked the button')"> </form>
The previous examples highlight only the simplest features of client-side JavaScript. They don't touch on its ability to access the hierarchy of objects that are based on the Web content.