Basic JavaScript Date and Time Functions
As the title implies, this tutorial will show you how to get the date and time from the visitor's computer and print them to the web page.
You'll learn two basic techniques:
1. How to create what's called a date object.
2. How to extract information from that date object; the hour, minute, month, year, and so forth.
A complete working example of what you'll learn here is near the end of this tutorial.
How To Create What's Called a Date Object
When a date object is created, it is stored in what's called a variable. A variable is simply the name of a place in memory that can contain information. In our example, we'll call that variable "now" because it's a good name for the current date and time.
This is how you create a date object and store it in a variable:
var now = new Date();
The "new Date()" part of the above statement creates the date object. The "var now =" part causes the date object to be stored in the variable named "now".
How To Extract Information From that Date Object
Lots of information can be extracted from a date object. In this tutorial, we'll extract only what we'll need:
var hour var minute var second var monthnumber var monthday var year |
= now.getHours(); = now.getMinutes(); = now.getSeconds(); = now.getMonth(); = now.getDate(); = now.getYear(); |
Notice that the name of the variable containing the date object and a period are followed by the function name. The function extracts the information from the date object and stores it in the variable named on the left of the equal sign.
All of the function names are intuitive except getDate(), which gets the day of the month rather than a date. Do not confuse "getDate()" with "new Date()" -- the former, as stated, extracts the day of the month from a date object. The latter creates the date object itself.
Printing the Date and Time
The example near the end of this tutorial demonstrates one method of obtain the date and time and printing it on a web page.
The Date
To get the date, the complete working example further below has a function called getCalendarDate()
The first 13 lines of the function creates an array containing the names of the calendar month. The value obtained from the now.getMonth() function is used to determine which month name to use. The line that does that is
var monthname = months[monthnumber];
When now.getMonth() extracts a month number, it assumes January is number 0 and December is number 11. If you prefer to print the number of the month instead of the name of the month, replace the above line with
monthnumber = monthnumber + 1;
to conform the month number with the way most humans count them (January = 1, etc.).
The getCalendarDate() function also has a line to adjust the year if the visitor is using an older browser that still assumes we're living in the 1900's. You'll recognize the line when you read the code.
getCalendarDate() constructs a string of characters representing the calendar date. It then returns that construction to whatever JavaScript code calls the function.
The Time
To get the time, the complete working example further below has a function called getClockTime() getClockTime() includes code to format the clock time into an "AM" or "PM" representation. The following four lines accomplish that.
var ap = "AM"; if (hour > 11) if (hour > 12 )if (hour == 0) |
{ ap = "PM"; }
{ hour = hour - 12; } { hour = 12; } |
If you want the clock time to represent a 24-hour clock instead of an "AM/PM" representation, simply remove those four lines from the function.
getClockTime() constructs a string of characters representing the clock time. It then returns that construction to whatever JavaScript code calls the function. If you don't want the construction to include the "AM" or "PM" part, remove the last two lines from the code that constructs the clock time.
The Printing
To print the date and time, use JavaScript to call the getCalendarDate() and getClockTime() functions. Then print the strings of characters they return. Example:
<script type="text/javascript" language="JavaScript"><!--
var calendarDate = getCalendarDate();
var clockTime = getClockTime();
document.write('Date is ' + calendarDate);
document.write('<br>');
document.write('Time is ' + clockTime);
//--></script> |
The Complete Working Example
Here is a web page that incorporates everything this tutorial has mentioned.
Note that JavaScript is line break sensitive. Thus, it's best to keep the lines as they are, at least until you are ready to do custom modifications.
<html>
<head>
<script type="text/javascript" language="JavaScript">
<!-- Copyright 2002 Bontrager Connection, LLC
function getCalendarDate()
{
var months = new Array(13);
months[0] = "January";
months[1] = "February";
months[2] = "March";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "August";
months[8] = "September";
months[9] = "October";
months[10] = "November";
months[11] = "December";
var now = new Date();
var monthnumber = now.getMonth();
var monthname = months[monthnumber];
var monthday = now.getDate();
var year = now.getYear();
if(year < 2000) { year = year + 1900; }
var dateString = monthname +
' ' +
monthday +
', ' +
year;
return dateString;
} // function getCalendarDate()
function getClockTime()
{
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var ap = "AM";
if (hour > 11) { ap = "PM"; }
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (hour < 10) { hour = "0" + hour; }
if (minute < 10) { minute = "0" + minute; }
if (second < 10) { second = "0" + second; }
var timeString = hour +
':' +
minute +
':' +
second +
" " +
ap;
return timeString;
} // function getClockTime()
//-->
</script>
</head>
<body>
<script type="text/javascript" language="JavaScript"><!--
var calendarDate = getCalendarDate();
var clockTime = getClockTime();
document.write('Date is ' + calendarDate);
document.write('<br>');
document.write('Time is ' + clockTime);
//--></script>
</body>
</html> |
That's the complete working example. Create a file with the example and load it into your browser.
Functions getCalendarDate() and getClockTime() can be used wherever you need to extract the calendar date or clock time. While outside the scope of this tutorial, those results can be used in status bars, form fields, and other locations such as the title bar and in applications with layers. The time can be continuously updated by repeatedly calling the getClockTime() and printing the latest results.
With the above example, you have the basics to build your own calendars and clocks. Form Required Fields JavaScript Check
You know how annoying it is when you click a "submit" button, wait for the next page to appear, and then all you get is the message, "___________ is required!" You fix that, and another field is required. And another.
Here is a method to let your form user know, all at once and before sending the information to a script, about each required form field that hasn't been filed in (or checked, or selected). See the demonstration page at http://willmaster.com/a/18/pl.pl?art188
A previous article, "Form Input Validation and Correction," demonstrated how to verify email addresses are correctly formatted and some other functions, including automatically upper- and lower-casing a name. You can find the article at http://willmaster.com/a/18/pl.pl?fivc
Here, you learn how to check any required form field, with each field having a custom error message for explaining to your user exactly what is expected.
The custom error messages are displayed in one alert box, which generally is faster than creating a popup window and generating a custom web page for it. Detailed instructions are in the source code downloadable from the demonstration page at http://willmaster.com/a/18/pl.pl?art188
The JavaScript functions can check not only any type of form field, but form field sets.
A field set is two or more form fields of the same type with the same name. Radio buttons are usually found in sets. However, checkboxes, text input fields, and even file upload fields can also be in sets.
The JavaScript has separate checking functions for text input fields, sets of text input fields, radio/checkbox fields, sets of radio/checkbox fields, and dropdown list/select box fields. Each function needs to know either the form field to check or the form field value to check.
Function WithoutContent() is used to check if a text input field is without content.
Function NoneWithContent() is used to check if none of a set of text input field have content.
Function WithoutCheck() is used to check if the single radio button or checkbox is unchecked.
Function NoneWithCheck() is used to check if none of a set of radio buttons or checkboxes are checked.
Function WithoutSelectionValue() is used to check if selected drop-down list or select box entries are without value.
Your form will have a name for itself, specified in the FORM tag. This form name will be used wherever a form field or form field value is specified.
For example, if your form name is "myname" and the form field name is "email", you would refer to that form field as
document.myname.email
And you would refer to that form field's value as
document.myname.email.value
The JavaScript is told to check required fields by putting the attribute onSubmit="return CheckRequiredFields()" into your FORM tag. (The demonstration has an example.) The JavaScript CheckRequiredFields() checks the required fields and returns either the value true or the value false.
If true, all required fields are used and the form continues it's normal form submit procedure. If false, the form does not submit the form contents.
In order to use this JavaScript, the only non-alphanumeric character your form field names may have is the underscore. Replace any hyphens, colons, spaces, or other non-alphanumeric characters in your field names with an underscore character.
Once your form field names are in compliance, make a list of the names of required form fields, along with the error message to display if the requirement isn't satisfied.
Then, continuing with the example email field, you would put this into the JavaScript at the place indicated by the instructions in the JavaScript: if(WithoutContent(document.myname.email.value)) { errormessage += "\n\nThe email address is required!"; }
Whenever the JavaScript finds one or more error messages, it gathers them all together into one message and displays them in an alert box under the heading "NOTE:". The \n\n in front of the error message puts a blank line between it and anything above it.
Testing
When you test the JavaScript, if you get no error message even if a required form field has not been satisfied, then either your browser isn't running JavaScript or your JavaScript has an error somewhere.
Netscape browsers (version 4 and higher) are wonderful JavaScript debugging tools; better, in my opinion, than other browser brands I've used. After loading the page and clicking submit, type
javascript:
in the browser's address bar. If there were errors, the browser usually provides a good indication of where and what the error is.
Conclusion
You have been introduced to a set of JavaScript functions you can customize to display a pertinent error message whenever one or more required form fields have not been used. Because the error messages are all in one quick alert box, instead of one at a time from a CGI script, the JavaScript can reduce form user annoyance when required information is omitted.
Random Images
Here is a really easy way to have random images for a page. Here are the four steps.
Step 1. Make your images.
When you make your images, they must all be of the same type, like .gif or .jpg
The image file names must all be the same except for an embedded sequential number. Examples:
logo1.jpg
logo2.jpg
logo3.jpg
It doesn't matter how many images you will be using so long as the naming is consistent and the numbers are sequential.
When your images are ready, upload them into a directory on your server.
Step 2. Determine the image tag.
Determine what your image tag would be if you were putting the image directly onto your page. You'll use this tag in the JavaScript function in the next step.
Here is an example image tag:
<img src="logo2.jpg">
If all of your images will have the same height and width, you might also include those in the image tag:
<img src="logo2.jpg" height="150" width="200">
Step 3. Create the JavaScript function.
Put this JavaScript into the HEAD area of your web page, like:
<HTML>
<HEAD>
<script type="text/javascript" language="JavaScript">
<!-- Copyright 2002 Bontrager Connection, LLC
//
// Type the number of images you are rotating.
NumberOfImagesToRotate = 3;
// Specify the first and last part of the image tag.
FirstPart = '<img src="logo';
LastPart = '.jpg" height="150" width="200">';
function printImage() {
var r = Math.ceil(Math.random() * NumberOfImagesToRotate);
document.write(FirstPart + r + LastPart);
}
//-->
</script>
</HEAD>
<BODY...
On the line with NumberOfImagesToRotate, replace the number 3 with the number of images you are rotating.
Now, use the last example in the previous step and separate the image tag into two parts. The first part will be the tag up to the sequential number. The last part will be everything following the sequential number. The number itself will not be represented in either the first or last part.
Between the apostrophes following "FirstPart =" and "LastPart =", put the first and last part of your image tag.
That's all you need to do with the JavaScript function. When called, the function will determine a random number from 1 to the NumberOfImagesToRotate. It will then construct the image tag by placing the random number between the FirstPart and LastPart. Last, it will print the constructed image tag with the built-in document.write() function.
Step 4. Insert the random image.
Where you want the random image to appear on your web page, put:
<script type="text/javascript" language="JavaScript"><!--
printImage();
//--></script>
That's all there's to it.
The demonstration page at http://willmaster.com/a/14/pl.pl?art141 contains three images for random insertion.
With only three images, there is a 1 in 3 chance that the same image will display when you reload the page. The more images you have for the randomizer to choose from, the less often the same image will display more than once in a row.
Instant Info
This article shows you how to code an instant information system that can place
• definitions,
• instructions, and
• other information
near your site visitor's cursor. The information appears when the cursor hovers over certain links or when certain form fields are clicked.
The information pre-loads as the web page loads. Thus, it can appear instantly.
This instant info system uses layers to present the info. If you would like to use alert boxes or popup windows instead, see the "FastInfo, Build Your Own JavaScript Pop-Up Windows" ebook, sold here [http://willmaster.com/a/17/pl.pl?pie4].
Why instant info? Here are examples of how it may be used:
1. As additional information related to a link, to be
presented when the cursor is over the link. For
example, your link might be "Best Widgets" and the
instant info could be "We searched far and wide for
the best of the best. This is it!"
2. You offer many colors of each item. To print them
all, would make your web page appear cluttered. With
this system, you could have a "Colors" link that
launches an instant list of colors.
3. You have a list of ingredients, parts, or other
components. The instant info for each component
could be a list of amount and quality required,
what it's function is, whether or not it's actually
necessary, substitution suggestions, alternate
measurements, and so forth.
4. Instant hints, for quiz or problem solving pages.
5. Instant explanation of what data is expected or
required, for form fields.
6. Instant help at any point on your web page.
The instructions are in this article instead of in the JavaScript. The JavaScript has instructions related only to the one section in the script that needs to be customized.
You implement it in three steps:
1. Create your web page with your instant info links
and/or instant info form fields.
2. Create the content that will be instantly available.
3. Install the JavaScript.
Each step requires the prior step to be completed.
If you prefer to have a complete example at hand as you go through the instructions, you'll find it linked from this page.
The code has been tested to work with IE 5, Netscape 4, Netscape 6, and Opera 6.
I. Creating Your Instant Info Links and Form Fields
For links, it is rather straight-forward. Go ahead and create the links.
If the href="____" attribute of any links do not contain a URL to another web page, replace the attribute with
href="javascript:Null()"
Once you've created the links, insert
onMouseover="LL_showinfo(1)" onMouseout="LL_hideallinfo()"
into each link anchor tags Example:
<a
href="javascript:Null()"
onMouseover="LL_showinfo(1)"
onMouseout="LL_hideallinfo()">
Something
</a>
See the number 1 between the parenthesis? The numbers need
to be sequential -- (1), (2), (3), and so forth. It would
look something like this:
<a
href="javascript:Null()"
onMouseover="LL_showinfo(1)"
onMouseout="LL_hideallinfo()">
Something
</a>
<a
href="javascript:Null()"
onMouseover="LL_showinfo(2)"
onMouseout="LL_hideallinfo()">
Something Else
</a>
<a
href="javascript:Null()"
onMouseover="LL_showinfo(3)"
onMouseout="LL_hideallinfo()">
Another
</a>
For form fields, add the following two attributes to the form field tag:
onFocus="LL_showinfo(1)" onBlur="LL_hideallinfo()"
That number (1) needs to be sequential with other instant info form fields and instant info links. Let's suppose you had three instant info links above a form, and your form has two instant info form fields. The form fields might look something like this:
Your Email:
<input
type="text"
name="email"
onFocus="LL_showinfo(4)"
onBlur="LL_hideallinfo()">
Your Telephone Number:
<input
type="text"
name="phone"
onFocus="LL_showinfo(5)"
onBlur="LL_hideallinfo()">
II. Creating the Instant Info Content
This needs to be done in two parts, creating a CSS Style in the HEAD area and creating the content itself in the BODY area.
A. The CSS Style
Put the following CSS Style into the HEAD area of your page:
<STYLE type="text/css">
<!--
.infoboxstyle {
position: absolute;
color: black;
border: black;
border-style: solid;
border-top-width: 1px;
border-bottom-width: 3px;
border-left-width: 6px;
border-right-width: 6px;
background-color: #EFEFEF;
z-index: 1;
visibility: hidden;
}
-->
</STYLE>
Now, let's customize it according to your preferences.
"infoboxstyle" is the style of the box containing the info content. Line by line, the style sheet rules in the example are:
"position: absolute;" is required, and it must remain
as is. This allows the JavaScript to place the
info box into exact positions on the web page.
"background-color: #EFEFEF;" is optional. Use it
when you want to specify a background color for the
info box. The color, as all colors in CSS, can be
specified in hexadecimal, like the example, as an
RGB value, or the color name.
"color: black;" is optional. Use it when you want
to specify a text color for the info box.
"border: black;" is optional. Use it when you want
to specify a color for a border around your info box.
border-style: solid;" is optional. Use it when you
want to specify a style for a border around your
info box. Other than "solid", attributes that can
be specified are "none", "dotted", "dashed", "double","groove", "ridge", "inset", and "outset".
"border-top-width: 6px;" is optional. When you want
to have a top border for your info box, specify the
number of pixels.
"border-bottom-width: 3px;" is optional. When you want
to have a bottom border for your info box, specify
the number of pixels.
"border-left-width: 1px;" is optional. When you want
to have a left border for your info box, specify the
number of pixels.
"border-right-width: 1px;" is optional. When you want
to have a right border for your info box, specify the
number of pixels.
"z-index: 1;" should be present. Although not strictly
required, this directs the browser to make this layer,
layer number one. (Your info box are layers.) Because
each sub-menu will be displayed independent of the
others, and only one sub-menu at a time, the number"1" is okay for all.
"visibility: hidden;" is required. Before you create
your info box (in the next step) change this to"visibility: show;" -- otherwise the browser won't
display your info box during your development phase.
Once the info box have been created, change this back
to "visibility: hidden;" so the info box won't be
displayed until the cursor travels over one of the main
menu links.
B. The Instant Info Content
The HTML markup for the instant info content should be placed immediately below the BODY tag. This is not necessarily the place where they will appear, since the content has specific location rules built in. The reason for placing the content immediately below the BODY tag is to ensure the browser reads the HTML markup before the content needs to be displayed.
Here is an example of instant info content:
<div
id="aDefinition"
style="top:1px; left:1px; width:65px; height:40px; padding:6;"
class="infoboxstyle">
The content goes here.
</div>
Now, let's customize it according to your preferences.
The first attribute is "id" and it is required. The value of "id" is a name you assign to that particular content. (The JavaScript uses this name to keep track of which content is which.)
The second attribute is "style" and is also required. Of the five rules in the example style's value, only "padding:__" is optional. The reason these particular style rules are specified as an in-line style is because the information is needed to calculate the display of the info box. Not all browser JavaScript engines can access the style rules specified in the HEAD area.
"top:1px" specifies the distance in pixels from the
top edge of the browser window to be the top left
corner of the instant info box to be displayed. Make
this 1px. The JavaScript will calculate positioning
when the instant info is displayed.
"left:1px" specifies the distance in pixels from the
left edge of the browser window to be the top left
corner of the instant info box to be displayed. Make
this 1px. The JavaScript will calculate positioning
when the instant info is displayed.
"width:65px;" specifies the width of the sub-menu to
be 65 pixels. Adjust as necessary, easier if you wait
until the JavaScript is in place and you're testing
the page.
"height:40px;" specifies the height of the sub-menu
to be 40 pixels. Adjust as necessary, easier if you
wait until the JavaScript is in place and you're
testing the page.
"padding:6;" is optional. It specifies the padding
you want between the border of the sub-menu and the
text within the border. It's expressed in pixels.
Adjust or omit as desired.
The third attribute is "class" and is required. It's value must be the same as the class created in the HEAD area for this purpose, "infoboxstyle" in our example.
III. Installing the JavaScript
At this point, unless you've already done so, pick up the JavaScript from the demonstration page [http://willmaster.com/a/17/pl.pl?art179] .
Paste the JavaScript into the HEAD area of your page.
Customize the JavaScript by specifying the "id" value of each instant info content item you created in step II, along with the sequential number related to the item.
The JavaScript has instructions and is, itself, an example of how to do it.
Now you have the tools to build a professional instant info system. If you prefer to use a popup system or a JavaScript alert system, see the "FastInfo, Build Your Own JavaScript Pop-Up Windows" ebook, sold here [http://willmaster.com/a/17/pl.pl?pie4] .
Whether you use the layers system presented in this article or one of the systems described in the above ebook, having appropriate information available the instant it's needed can give site visitors a good impression of your business.
By William Bontrager
About the Author:
William Bontrager Programmer/Publisher, "WillMaster Possibilities" ezine mailto:possibilities@willmaster.com
Are you looking for top quality scripts? Visit Willmaster [http://hop.clickbank.net/hop.cgi?nturavets/willmaster] and check out his highly acclaimed Master Series scripts. Some free, some for a fee.
|