23.3. JavaScript Examples

The following sections provide example documents that include scripts to perform various tasks. Each example is presented with source code, output, an explanation of how the script works, and ways that the script can be extended or improved.

The scripts in this section have been written and verified to run on the two most popular browsers: Mozilla Firefox 1.0 and Microsoft Internet Explorer 6.0+. To keep the examples straightforward and simple, no additional cross-platform coding has been added. However, the scripts should run on any user agent compatible with these two "standards."

23.3.1. Writing Text to a Document

One basic and often used JavaScript function is outputting text to the user agent window. Because JavaScript cannot access external resources, you are limited to the data objects built into JavaScript or otherwise present in the document.

Example 1: Writing the Current Date to the Current Document

This example shows how to output the current date into a document.

Source

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Display Date (Text)</title>
<script type="text/JavaScript"> // Set up arrays var months = new Array("January","February","March","April", "May","June","July","August","September","October", "November","December"); var days = new Array("Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"); function writedate() { // Get current ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.