Learn java scripts, Javascripts, Java, Java with examples.

Earn Money for free

Thursday, June 5, 2008

James Thiele's Reminder Calendar

James Thiele's Reminder Calendar

James Thiele has designed a simple reminder calendar as an example using cookies in JavaScript. The calendar is available at

http://www.eskimo.com/~jet/javascript/calendar_js.html

Rather than being a full-fledged application, this page provides simple functionality yet is a compelling example of how cookies can extend the value of a script beyond time and session constraints.

The program displays a calendar of the current month, much the same as in Dave Eisenberg's calendar example. When the user clicks on any of the days in the calendar, they either can enter a reminder for that day or they are alerted of their previously entered reminder.





When the user reloads the page or returns to it later in the month, the days with reminders are displayed in a different color.

Input

    Listing W4.1. Source code for James Thiele's Reminder Calendar.

Output

End of Output

Analysis

The first thing you will notice is that Thiele is using an early version of Bill Dortch's cookie function set. This version was written before JavaScript included the escape() and unescape() functions which forced Dortch to write his own functions, encode() and decode(), to perform the encoding of values.

In any case, the newer version of Dortch's functions are backward compatible and could replace the old version in this script without affecting its operation in newer browsers.

Thiele has written five functions to implement his calendar program: intro(), arrayOfDaysInMonth(), daysInMonth(), calendar(), and dayClick().

In addition, he builds most of the body of his HTML document using a JavaScript script:

This script is quite simple: it calls calendar() to display the calendar, it draws a horizontal line and then it calls intro() which displays most of the rest of the text of the script.

The intro() Function

This function needs little discussion. It is just a static collection of document.write() statements that output the introductory information about the application.

The arrayOfDaysInMonth() Function

The arrayOfDaysInMonth() function simply creates a 12-element array containing the number of days in each calendar month. It accepts one boolean variable as an argument. This enables it to correctly set the number of days in February based on whether or not it is a leap year.

The daysInMonth() Function

This function takes two arguments—the month and year—and uses these to determine if it is a leap year. It then creates an array of days in each month of the particular year and returns the number of days in the specified month.

The calendar() Function

The calendar() function is where some of the more complex processing occurs.

   var monthNames = "JanFebMarAprMayJunJulAugSepOctNovDec";


var today = new Date();

var day = today.getDate();

var month = today.getMonth();

var year = today.getYear() + 1900;

// figure out how many days this month will have...

var numDays = daysInMonth(month, year);

// and go back to the first day of the month...

var firstDay = today;

firstDay.setDate(1);

// and figure out which day of the week it hits...

var startDay = firstDay.getDay();

var column = 0;

As would be expected, the function starts by setting up key variables for use throughout the function. These include a string of month names, the same technique you saw in Dave Eisenberg's calendar script.

The firstDay Date object is used to get the day of the week of the first day of the month and store it in startDay.

   // Start the calendar table


document.write("
");

document.write("");

document.write("");

for (i=1; i <>");

column++;

}

After building the header of the table which holds the calendar for the month, the for loop inserts blank cells for each of the unused days of the week before the first day of the month.

   for (i=1; i <= numDays; i++)    {       // Write the day       var s = "" + i;       if ((GetCookie("d"+i) != null))         // s = s.fontcolor(document.vlinkColor);         s = s.fontcolor("#FF0000");         s = s.link("javascript:dayClick(" + i + ")")           document.write("
"); // start a new row

column = 0;

}

}

Next, another for loop repeats for each day in the month. For each day, a cell is created and the number is displayed with a hypertext link to the URL javascript:dayClick(number). This is done by using the string's link method to add the URL. As you will see in Chapter 10, "Strings, Math and the History List," if the link method is used then the value of the string is surrounded by an appropriate HTML container tag.


Notice the use of the javascript: URL. This type of URL can be used to call a function in the current document. When used in the HREF attribute of the tag, this is often an alternative to using the onClick event handler. It can also be used in the open location dialog box of the Navigator browser to test what a line of JavaScript code will evaluate to. In this case, the result of evaluating an expression is displayed in the browser window.

Similarly, the fontcolor() method adds the appropriate HTML tags to the value of the string. In this case, the fontcolor() method is only called if the cookie for that day has been previously set with a reminder.

The final if statement checks if you have reached the last column, and if so, closes the row, opens a new row in the table, and resets the column counter.

The dayClick() Function

This function handles both prompting for a reminder and displaying existing reminders. It is invoked when the user clicks on a date. It accepts the date as an argument.

        var expdate = new Date ();


expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000)); // 24 hrs from now

var prefix = "d";

var theCookieName = prefix + day;

var theDayclickedReminder = GetCookie(theCookieName);

The function starts by setting up its variables, including an expiry date for cookies and a value of the cookie for the selected date.

    if (theDayclickedReminder != null) {


alert("The reminder for day " + day + " is:" + theDayclickedReminder);

} // end if

If the value of the cookie is not null, then the reminder is displayed in an alert dialog box.

        if (confirm("Do you wish to enter a reminder for day " + day + " of this month?"))


{

x = prompt("Enter a reminder for day "+ day + " of this month", theDayclickedReminder);

SetCookie (theCookieName, x, expdate);

} // end if

If the value of the cookie is null, then users are asked if they wish to enter a reminder for the current day and, if they do, they are further prompted for the text of the reminder. The reminder is then stored in a cookie. Notice the use of the confirm() call as the condition of the if statement—confirm() returns a value of true or false based on the user's response.

");

document.write(monthNames.substring(3*month, 3*(month + 1)) + " " + year);

document.write("
SunMonTueWedThuFriSat");

// put blank table entries for days of week before beginning of the month

document.write("
" + s);

// Check for end of week/row

if (++column == 7)

{

document.write("

JavaScript Language Reference

JavaScript Language Reference

The first part of this reference is organized by object with properties and methods listed by the object they apply to. The second part covers independent functions in JavaScript not connected with a particular object, as well as operators in JavaScript.

The anchor Object

See the anchors property of the document object.

The button Object

The button object reflects a push button from an HTML form in JavaScript.

Properties

  • name A string value containing the name of the button element.

  • value A string value containing the value of the button element.

Methods

  • click() Emulates the action of clicking on the button.

Event Handlers

  • onClick Specifies JavaScript code to execute when the button is clicked.

The checkbox Object

The checkbox object makes a checkbox from an HTML form available in JavaScript.

Properties

  • checked A boolean value indicating if the checkbox element is checked.

  • defaultChecked A boolean value indicating if the checkbox element was checked by default (i.e. reflects the CHECKED attribute).

  • name A string value containing the name of the checkbox element.

  • value A string value containing the value of the checkbox element.

Methods

  • click() Emulates the action of clicking on the checkbox.

Event Handlers

  • onClick Specifies JavaScript code to execute when the checkbox is clicked.

The Date Object

The Date object provides mechanisms for working with dates and times in JavaScript. Instances of the object can be created with the syntax

newObjectName = new Date(dateInfo)

Where dateInfo is an optional specification of a particular date and can be one of the following:

"month day, year hours:minutes:seconds"

year, month, day

year, month, day, hours, minutes, seconds

where the later two options represent integer values.

If no dateInfo is specified, the new object will represent the current date and time.

Methods

  • getDate() Returns the day of the month for the current Date object as an integer from 1 to 31.

  • getDay() Returns the day of the week for the current Date object as an integer from 0 to 6 (where 0 is Sunday, 1 is Monday, etc.).

  • getHours() Returns the hour from the time in the current Date object as an integer from 0 to 23.

  • getMinutes() Returns the minutes from the time in the current Date object as an integer from 0 to 59.

  • getMonth() Returns the month for the current Date object as an integer from 0 to 11 (where 0 is January, 1 is February, etc.).

  • getSeconds() Returns the seconds from the time in the current Date object as an integer from 0 to 59.

  • getTime() Returns the time of the current Date object as an integer representing the number of milliseconds since 1 January 1970 at 00:00:00.

  • getTimezoneOffset() Returns the difference between the local time and GMT as an integer representing the number of minutes.

  • getYear() Returns the year of the week for the current Date object as a two-digit integer representing the year less 1900.

  • parse(dateString) Returns the number of milliseconds between January 1, 1970 at 00:00:00 and the date specified in dateString. dateString should take the format

Day, DD Mon YYYY HH:MM:SS TZN

Mon DD, YYYY

  • setDate(dateValue) Sets the day of the month for the current Date object. dateValue is an integer from 1 to 31.

  • setHours(hoursValue) Sets the hours for the time for the current Date object. hoursValue is an integer from 0 to 23.

  • setMinutes(minutesValue) Sets the minutes for the time for the current Date object. minutesValue is an integer from 0 to 59.

  • setMonth(monthValue) Sets the month for the current Date object. monthValue is an integer from 0 to 11 (where 0 is January, 1 is February, etc.).

  • setSeconds(secondsValue) Sets the seconds for the time for the current Date object. secondsValue is an integer from 0 to 59.

  • setTime(timeValue) Sets the value for the current Date object. timeValue is an integer representing the number of milliseconds since January 1, 1970 at 00:00:00.

  • setYear(yearValue) Sets the year for the current Date object. yearValue is an integer greater than 1900.

  • toGMTString() Returns the value of the current Date object in GMT as a string using Internet conventions in the form

Day, DD Mon YYYY HH:MM:SS GMT

  • toLocaleString() Returns the value of the current Date object in the local time using local conventions.

  • UTC(yearValue, monthValue, dateValue, hoursValue, minutesValue, secondsValue) Returns the number of milliseconds since January 1, 1970 at 00:00:00 GMT. yearValue is an integer greater than 1900. monthValue is an integer from 0 to 11. dateValue is an integer from 1 to 31. hoursValue is an integer from 0 to 23. minutesValue and secondsValue are integers from 0 to 59. hoursValue, minutesValue and secondsValue are optional.

The document Object

The document object reflects attributes of an HTML document in JavaScript.

Properties

  • alinkColor The color of active links as a string or a hexadecimal triplet.

  • anchors Array of anchor objects in the order they appear in the HTML document. Use anchors.length to get the number of anchors in a document.

  • bgColor The color of the document's background.

  • cookie A string value containing cookie values for the current document.

  • fgColor The color of the document's foreground.

  • forms Array of form objects in the order the forms appear in the HTML file. Use forms.length to get the number of forms in a document.

  • lastModified String value containing the last date of modification of the document.

  • linkColor The color of links as a string or a hexadecimal triplet.

  • links Array of link objects in the order the hypertext links appear in the HTML document. Use links.length to get the number of links in a document.

  • location A string containing the URL of the current document.

  • referrer A string value containing the URL of the calling document when the user follows a link.

  • title A string containing the title of the current document.

  • vlinkColor The color of followed links as a string or a hexadecimal triplet.

Methods

  • clear() Clears the document window.

  • close() Closes the current output stream.

  • open(mimeType) Opens a stream which allows write() and writeln() methods to write to the document window. mimeType is an optional string which specifies a document type supported by Navigator or a plug-in (i.e. text/html, image/gif, etc.).

  • write() Writes text and HTML to the specified document.

  • writeln() Writes text and HTML to the specified document followed by a newline character.

The form Object

The form object reflects an HTML form in JavaScript. Each HTML form in a document is reflected by a distinct instance of the form object.

Properties

Methods

  • submit() Submits the form.

Event Handlers

  • onSubmit Specifies JavaScript code to execute when the form is submitted. The code should return a true value to allow the form to be submitted. A false value prevents the form from being submitted.

The frame Object

The frame object reflects a frame window in JavaScript.

Properties

  • frames An array of objects for each frame in a window. Frames appear in the array in the order in which they appear in the HTML source code.

  • parent A string indicating the name of window containing the frameset.

  • self A alternative for the name of the current window.

  • top An alternative for the name of the top-most window.

  • window An alternative for the name of the current window.

Methods

  • alert(message) Displays message in a dialog box.

  • close() Closes the window.

  • confirm(message) Displays message in a dialog box with OK and CANCEL buttons. Returns true or false based on the button clicked by the user.

  • open(url,name,features) Opens url in a window named name. If name doesn't exist, a new window is created with that name. features is an optional string argument containing a list of features for the new window. The feature list contains any of the following name-value pairs separated by commas and without additional spaces:

toolbar=[yes,no,1,0]

Indicates if the window should have a toolbar

location=[yes,no,1,0]

Indicates if the window should have a location field

directories=[yes,no,1,0]

Indicates is the window should have directory buttons

status=[yes,no,1,0]

Indicates if the window should have a status bar

menubar=[yes,no,1,0]

Indicates if the window should have menus

scrollbars=[yes,no,1,0]

Indicates if the window should have scroll bars

resizable=[yes,no,1,0]

Indicates if the window should be resizable

width=pixels

Indicates the width of the window in pixels

height=pixels

Indicates the height of the window in pixels
  • prompt(message,response) Displays message in a dialog box with a text entry field with the default value of response. The user's response in the text entry field is returned as a string.

  • setTimeout(expression,time) Evaluates expression after time where time is a value in milliseconds. The time out can be named with the structure:

name = setTimeOut(expression,time)

The hidden Object

The hidden object reflects a hidden field from an HTML form in JavaScript.

Properties

  • name A string value containing the name of the hidden element.

  • value A string value containing the value of hidden text element.

The history Object

The history object allows a script to work with the Navigator browser's history list in JavaScript. For security and privacy reasons, the actual content of the list is not reflected into JavaScript.

Properties

  • length An integer representing the number of items on the history list.

Methods

  • back() Goes back to the previous document in the history list.

  • forward() Goes forward to the next document in the history list.

  • go(location) Goes to the document in the history list specified by location. location can be a string or integer value. If it is a string it represents all or part of a URL in the history list. If it is an integer, location represents the relative position of the document on the history list. As an integer, location can be positive or negative.

The link object

The link object reflects a hypertext link in the body of a document.

Properties

  • target A string value containing the name of the window or frame specified in the TARGET attribute.

Event Handlers

  • onClick Specifies JavaScript code to execute when the link is clicked.

  • onMouseOver Specifies JavaScript code to execute when the mouse is over the hypertext link

The location Object

The location object reflects information about the current URL.

Properties

  • hash A string value containing the anchor name in the URL.

  • host A string value containing the hostname and port number from the URL.

  • hostname A string value containing the domain name (or numerical IP address) from the URL.

  • href A string value containing the entire URL.

  • pathname A string value specifying the path portion of the URL.

  • port A string value containing the port number from the URL.

  • protocol A string value containing the protocol from the URL (including the colon, but not the slashes).

  • search A string value containing any information passed to a GET CGI-BIN call (i.e. an information after the question mark).

The Math Object

The Math object provides properties and methods for advanced mathematical calculations.

Properties

  • E The value of Euler's constant (roughly 2.718) used as the base for natural logarithms.

  • LN10 The value of the natural logarithm of 10 (roughly 2.302).

  • LN2 The value of the natural logarithm of 2 (roughly 0.693).

  • PI The value of PI—used in calculating the circumference and area of circles (roughly 3.1415).

  • SQRT1_2 The value of the square root of one-half (roughly 0.707).

  • SQRT2 The value of the square root of two (roughly 1.414).

Methods

  • abs(number) Returns the absolute value of number. The absolute value is the value of a number with it's sign ignored so abs(4) and abs(-4) both return 4

  • acos(number) Returns the arc cosine of number in radians.

  • asin(number) Returns the arc sine of number in radians.

  • atan(number) Returns the arc tangent of number in radians.

  • ceil(number) Returns the next integer greater than number—in other words, rounds up to the next integer.

  • cos(number) Returns the cosine of number where number represents an angle in radians.

  • exp(number) Returns the value of E to the power of number.

  • floor(number) Returns the next integer less than number—in other words, rounds down to the nearest integer.

  • log(number) Returns the natural logarithm of number.

  • max(number1,number2) Returns the greater of number1 and number2.

  • min(number1,number2) Returns the smaller of number1 and number2.

  • pow(number1,number2) Returns the value of number1 to the power of number2.

  • random() Returns a random number between zero and one (at press time, this method only was available on UNIX versions of Navigator 2.0).

  • round(number) Returns the closest integer to number—in other words rounds to the closest integer.

  • sin(number) Returns the sine of number where number represents an angle in radians.

  • sqrt(number) Returns the square root of number.

  • tan(number) Returns the tangent of number where number represents an angle in radians.

The navigator object

The navigator object reflects information about the version of Navigator being used.

Properties

  • appCodeName A string value containing the code name of the client (i.e. "Mozilla" for Netscape Navigator).

  • appName A string value containing the name of the client (i.e. "Netscape" for Netscape Navigator).

  • appVersion A string value containing the version information for the client in the form

    versionNumber (platform; country)

    For instance, Navigator 2.0, beta 6 for Windows 95 (international version), would have an appVersion property with the value "2.0b6 (Win32; I)".

  • userAgent A string containing the complete value of the user-agent header sent in the HTTP request. This contains all the information in appCodeName and appVersion:

    Mozilla/2.0b6 (Win32; I)

The password Object

The password object reflects a password text field from an HTML form in JavaScript.

Properties

  • defaultValue A string value containing the default value of the password element (i.e. the value of the VALUE attribute).

  • name A string value containing the name of the password element.

  • value A string value containing the value of the password element.

Methods

  • focus() Emulates the action of focusing in the password field.

  • blur() Emulates the action of removing focus from the password field.

  • select() Emulates the action of selecting the text in the password field.

The radio Object

The radio object reflects a set of radio buttons from an HTML form in JavaScript. To access individual radio buttons, use numeric indexes starting at zero. For instance, individual buttons in a set of radio buttons named testRadio could be referenced by testRadio[0], testRadio[1], etc.

Properties

  • checked A boolean value indicating if a specific button is checked. Can be used to select or deselect a button.

  • defaultChecked A boolean value indicating if a specific button was checked by default (i.e. reflects the CHECKED attribute).

  • length An integer value indicating the number of radio buttons in the set.

  • name A string value containing the name of the set of radio buttons.

  • value A string value containing the value a specific radio button in a set (i.e. reflects the VALUE attribute).

Methods

  • click() Emulates the action of clicking on a radio button.

Event Handlers

  • onClick Specifies JavaScript code to execute when a radio button is clicked.

The reset Object

The reset object reflects a reset button from an HTML form in JavaScript.

Properties

  • name A string value containing the name of the reset element.

  • value A string value containing the value of the reset element.

Methods

  • click() Emulates the action of clicking on the reset button.

Event Handlers

  • onClick Specifies JavaScript code to execute when the reset button is clicked.

The select Object

The select object reflects a selection list from an HTML form in JavaScript.

Properties

  • length An integer value containing the number of options in the selection list.

  • name A string value containing the name of the selection list.

  • options An array reflecting each of the options in the selection list in the order they appear. The options property has it's own properties:

defaultSelected

A boolean value indicating if an option was selected by default (i.e. reflects the SELECTED attribute).

index

An integer value reflecting the index of an option.

length

An integer value reflecting the number of options in the selection list.

name

A string value containing the name of the selection list.

options

A string value containing the full HTML code for the selection list.

selected

A boolean value indicating if the option is selected. Can be used to select or deselect an option.

selectedIndex

An integer value containing the index of the currently selected option.

text

A string value containing the text displayed in the selection list for a particular option.

value

A string value indicating the value for the specified option (i.e. reflects the VALUE attribute).
  • selectedIndex Reflects the index of the currently selected option in the selection list.

Event Handlers

  • onBlur Specifies JavaScript code to execute when the selection list loses focus.

  • onFocus Specifies JavaScript code to execute when focus is given to the selection list.

  • onChange Specifies JavaScript code to execute when the selected option in the list changes.

The string Object

The string object provides properties and methods for working with string literals and variables.

Properties

  • length An integer value containing the length of the string expressed as the number of characters in the string.

Methods

  • anchor(name) Returns a string containing the value of the string object surrounded by an A container tag with the NAME attribute set to name.

  • big() Returns a string containing the value of the string object surrounded by a BIG container tag.

  • blink() Returns a string containing the value of the string object surrounded by a BLINK container tag.

  • bold() Returns a string containing the value of the string object surrounded by a B container tag.

  • charAt(index) Returns the character at the location specified by index.

  • fixed() Returns a string containing the value of the string object surrounded by a FIXED container tag.

  • fontColor(color) Returns a string containing the value of the string object surrounded by a FONT container tag with the COLOR attribute set to color where color is a color name or an RGB triplet.

  • fontSize(size) Returns a string containing the value of the string object surrounded by a FONTSIZE container tag with the size set to size.

  • indexOf(findString,startingIndex) Returns the index of the first occurrence of findString, starting the search at startingIndex where startingIndex is optional—if it is not provided, the search starts at the start of the string.

  • italics() Returns a string containing the value of the string object surrounded by an I container tag.

  • lastIndexOf(findString,startingIndex) Returns the index of the last occurrence of findString. This is done by searching backwards from startingIndex. startingIndex is optional and assumed to be the last character in the string if no value is provided.

  • link(href) Returns a string containing the value of the string object surrounded by an A container tag with the HREF attribute set to href.

  • small() Returns a string containing the value of the string object surrounded by a SMALL container tag.

  • strike() Returns a string containing the value of the string object surrounded by a STRIKE container tag.

  • sub() Returns a string containing the value of the string object surrounded by a SUB container tag.

  • substring(firstIndex,lastIndex) Returns a string equivalent to the substring starting at firstIndex and ending at the character before lastIndex. If firstIndex is greater than lastIndex, the string starts at lastIndex and ends at the character before firstIndex.

  • sup() Returns a string containing the value of the string object surrounded by a SUP container tag.

  • toLowerCase() Returns a string containing the value of the string object with all character converted to lower case.

  • toUpperCase() Returns a string containing the value of the string object with all character converted to upper case.

The submit Object

The submit object reflects a submit button from an HTML form in JavaScript.

Properties

  • name A string value containing the name of the submit button element.

  • value A string value containing the value of the submit button element.

Methods

  • click() Emulates the action of clicking on the submit button.

Event Handlers

  • onClick Specifies JavaScript code to execute when the submit button is clicked.

The text Object

The text object reflects a text field from an HTML form in JavaScript.

Properties

  • defaultValue A string value containing the default value of the text element (i.e. the value of the VALUE attribute).

  • name A string value containing the name of the text element.

  • value A string value containing the value of the text element.

Methods

  • focus() Emulates the action of focusing in the text field.

  • blur() Emulates the action of removing focus from the text field.

  • select() Emulates the action of selecting the text in the text field.

Event Handlers

  • onBlur Specifies JavaScript code to execute when focus is removed from the field.

  • onChange Specifies JavaScript code to execute when the content of the field is changed.

  • onFocus Specifies JavaScript code to execute when focus is given to the field.

  • onSelect Specifies JavaScript code to execute when the user selects some or all of the text in the field.

The textarea Object

The textarea object reflects a multi-line text field from an HTML form in JavaScript.

Properties

  • defaultValue A string value containing the default value of the textarea element (i.e. the value of the VALUE attribute).

  • name A string value containing the name of the textarea element.

  • value A string value containing the value of the textarea element.

Methods

  • focus() Emulates the action of focusing in the textarea field.

  • blur() Emulates the action of removing focus from the textarea field.

  • select() Emulates the action of selecting the text in the textarea field.

Navigator 2.0 Is More Than a Web Browser

Navigator 2.0 Is More Than a Web Browser

Although Netscape Navigator started out its life as a basic Web browser, as it has grown increasingly popular, it has become much more.

Unlike earlier browsers and today's basic Web applications, Navigator 2.0 provides authors with numerous tools to step beyond the traditional constraints of HTML. Instead of simply combining text, pictures, sound and video, authors now have finer control over document layout, fonts, and color; they are able to extend the functionality of the browser using plug-ins and Java; and they can produce interactive applications using JavaScript.

A quick look at the Netscape Web site shows that today's Navigator can do so much more than previous versions—even without special programming by Web developers. With freely available plug-ins from leading software companies, Web authors can include native CorelDRAW graphics or Microsoft Word files in their documents, as well as view VRML (Virtual Reality Modeling Language) worlds, and view documents formatted in Adobe's device-independent Acrobat format.

On top of all this, however, Navigator 2.0 provides several tools that Web page developers and authors can take advantage of to enhance their documents and add dynamic interaction with the information they are providing on the Internet.