More frequently sought solutions

Our esteemed columnist tackles 10 more of your most common JavaScript questions

Last November, the JavaScript column in this illustrious publication presented a series of "frequently sought solutions" -- 10 of the most commonly asked-for JavaScript code solutions. The column struck a nerve and you asked for more. I can't turn away such a worthy bunch, so this month, we'll tackle 10 more frequently asked questions. Specifically, we'll find out how to:

  • Pass a nonstandard number of parameters to one function
  • Play a script when starting Netscape
  • Link to one page for JavaScript browsers and another page for other browsers
  • Process a link before loading a new document
  • Display a link for JavaScript users only
  • Use string methods with the window.location object
  • Display a clock on a page
  • Display the document source/document info windows
  • Link to a different page if the user's browser does not support JavaScript
  • Wait for a period of time before executing JavaScript code

That's a lot to cover, so let's get going. SUBHEAD: Pass a nonstandard number of parameters to one function Functions are typically "formally" declared to accept a certain number of parameters, and standard programming practice dictates that you always call a function with the right number of parameters. For example, this script uses a showMessage function that is formally declared to accept two parameters -- Message1 and Message2 -- which are used as messages in an alert box:

<![if !supportEmptyParas]> <![endif]>
showMessage ("Hello", "There");
<![if !supportEmptyParas]> <![endif]>
function showMessage (Message1, Message2) {
      alert (Message1);
      alert (Message2);
}

But JavaScript is more flexible than this. You can define a function with no formal list of parameters and call it using any number of parameters -- or no parameters, if you wish. JavaScript supports a special arguments object -- an array -- that is created inside a function. In addition to a length array that specifies the number of arguments passed to the function, each element of the array is a separate parameter passed to the function from the original "caller." For example, if you pass the revised showMessage function two parameters, the arguments object contains these values:

<![if !supportEmptyParas]> <![endif]>
arguments.length = 2
arguments[0] = "Hello"
arguments[1] = "There"

Code inside your function can determine how many arguments to process, and then go through the arguments array, one element at a time, and pick out the arguments that were passed to the function. Here's the revised version of the showMessage function, which is able to accept any number of parameters:

<![if !supportEmptyParas]> <![endif]>
showMessage ("Hello", "There");
showMessage ("Hello", "There", "Again!");
<![if !supportEmptyParas]> <![endif]>
function showMessage () {
      for (var Count = 0; Count < showMessage.arguments.length; Count++) {
              alert (showMessage.arguments[Count]);
      }
}

JavaScript also supports a caller property of the arguments object. This property contains the object string of the function that called this function. This means that you can use the caller property to determine the name of the "calling" function, and then use that name to determine what course of action to take. You might have your function do one thing if X function calls it, and do something else if Y function calls it. Here's a short demonstration of the caller property, along with some code to extract just the name of the calling function. This name is displayed in an alert box:

<![if !supportEmptyParas]> <![endif]>
<SCRIPT>
function processMessage () {
showMessage ("Hello", "There");
}
<![if !supportEmptyParas]> <![endif]>
function showMessage () {
      var Temp = showMessage.arguments.caller.toString()
      Ret = Temp.substring (Temp.indexOf (" "), Temp.indexOf ("("))
      alert (Ret)
}
<![if !supportEmptyParas]> <![endif]>
</SCRIPT>
<FORM>
<INPUT TYPE="button" VALUE="Click" onClick="processMessage()">
<INPUT TYPE="button" VALUE="Click" onClick="showMessage()">
</FORM>

SUBHEAD: Play a script when starting Netscape You can play a script when first starting Netscape if you set the Start With option to point to a local home page that contains the JavaScript you want to use. For example, the following script displays a welcome message when the local home page is loaded:

<![if !supportEmptyParas]> <![endif]>
<HTML><HEAD>
<TITLE>Local Home Page</TITLE>
</HEAD>
<SCRIPT>
function greetings() {
      alert ("Howdy!")
}
</SCRIPT>
<BODY onLoad="greetings()">
More body stuff here...
</BODY></HTML>

To set the local home page in Netscape, follow these simple steps:

  1. Choose "Options," "General Preferences."
  2. Click on the Appearance tab, and choose Home Page Location for the Start With option.
  3. Fill in the path and name of the local home page you want. For example, on a PC you would use the syntax:

file://c|/javascript/homepage.htm

SUBHEAD: Link to one page for JavaScript browsers and another page for other browsers A variation on the previous theme is how to provide a single link that directs JavaScript browsers one way, and non-JavaScript browsers the other way. The solution is easy: simply provide the non-JavaScript link in the HREF= attribute of the link then change to the new URL for the onClick event handler. The following example links to the "nojs.htm" page for non-JavaScript browsers, and "yesjs.htm" for JavaScript browsers:

<![if !supportEmptyParas]> <![endif]>
<A HREF="nojs.htm" onClick="this.href='yesjs.htm'">Click</A>

SUBHEAD: Process a link before loading a new document The example shown here allows you to process a link before loading a new document. The technique uses the JavaScript: protocol as the HREF of the link to call a JavaScript function. In this case, the function is processLink, and the HREF appears as:

<![if !supportEmptyParas]> <![endif]>
<A HREF="JavaScript:processLink">

The processLink function contains an alert box that represents whatever processing you want to do before linking to a new URL. In the next line, the code sets the location property to the desired URL you want to go to, as shown here:

<![if !supportEmptyParas]> <![endif]>
<HTML>
<HEAD>
<TITLE>Process Link First</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function processLink (form)  {
      alert ("Process steps here");
      location = "somepage.html";
}
</SCRIPT>
</HEAD>
<BODY>
<A HREF="JavaScript:processLink()">Click here</A>
</BODY>
</HTML>

Note that when you place the mouse over the link, the status bar displays the HREF, which says "JavaScript:processLink()." One practical application of this approach is to ask the user if she really wants to link to a new page (or display a large graphic or sound). The processLink function would then contain:

<![if !supportEmptyParas]> <![endif]>
function processLink (form)  {
      if (confirm("Do you want to link to the sound file (145K)?"));
              location = "http://mydomain.com/somesound.au/";
}

The confirm box displays a question with Yes and No buttons. If the answer is Yes, the sound is loaded. If the answer is no, the location instruction is skipped and the sound is not loaded. Another method for "pre-processing" a link uses links that are defined with the same HREF and NAME. This technique allows the anchor to link to itself. The advantage of this method is that you can avoid the display of the JavaScript URL.

<![if !supportEmptyParas]> <![endif]>
<A HREF="#1" NAME="1" onClick="processLink()">

SUBHEAD: Display a link for JavaScript users only By putting the text for a link in JavaScript code, you can display a link for only those users with JavaScript. The technique works like this:

<![if !supportEmptyParas]> <![endif]>
<SCRIPT>
<!-- hide from other browsers
document.write ('<A HREF="myurl.html">Click here, JavaScripters! </A>')
//-->
</SCRIPT>

Only those browsers with JavaScript will render the hypertext link. This feature gives you the advantage of custom-designing your pages so that those without JavaScript aren't even aware of the JavaScript-only features of your page. SUBHEAD: Use string methods with the window.location object The window.location object returns the URL of the current document in the window. (Note: window.location is the same as just plain location, assuming you're referring to the current window; that's exactly what we'll assume for the remainder of this section). You can see this URL string with some simple code:

<![if !supportEmptyParas]> <![endif]>
Ret = location;
alert (Ret);

Often, you'll want to manipulate the string returned by the location object. But if you try something like this

<![if !supportEmptyParas]> <![endif]>
Ret = location;
LastFour = Ret.substring (Ret.length-4, Ret.length);
alert (LastFour);

you'll get an error ("length is not a member"). You'll get different errors depending on what string methods you try to use. Remember that location is an object, even though it seems to return a string value -- in fact, a value you can readily see using the alert box. In order to manipulate this value with string methods, you'll need to convert it to a real string. One way to accomplish this conversion is to append the toString function to the end of the location object. Using this approach, the previous script will work just fine, as shown here:

<![if !supportEmptyParas]> <![endif]>
Ret = location.toString();
LastFour = Ret.substring (Ret.length-4, Ret.length);
alert (LastFour);

Another approach is to use the href property of the location object, as in:

<![if !supportEmptyParas]> <![endif]>
Ret = location.href;

And still another method is to use the location property of the document object, which (depending on circumstances) returns the same URL. The syntax is:

<![if !supportEmptyParas]> <![endif]>
Ret = document.location

SUBHEAD: Display a clock on a page A fairly common application for JavaScript is displaying a clock on the page. It's easy to do and mildly useful. I know of a number of different ways you can implement a clock, several are a bit too high-tech and involved for these virtual pages, but one solution will work just fine. This lower-tech technique for displaying the current time uses a form text box to keep the time updated. I wrote the following script so it would be fairly easy to modify. For example, you can readily alter it so it returns 24-hour time rather than 12-hour time, and you can change the period of updating from once every 30 seconds to a longer or shorter interval.

<![if !supportEmptyParas]> <![endif]>
<HTML>
<HEAD>
<TITLE>Clock Set</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function setClock() {
      now = new Date();
      var CurHour = now.getHours();
      var CurMinute = now.getMinutes();
      now = null;
              if (CurHour >= 12) {
              CurHour = CurHour - 12;
            Ampm = "pm";
      } else
              Ampm = "am";
      if (CurHour == 0)
      CurHour = "12"
      CurHour = ""+CurHour;
      Time= CurHour + ":" + CurMinute + Ampm
      document.clocktext.clock.value = Time
      setTimeout ("setClock()", 1000 * 30)
}
</SCRIPT>
</HEAD>
<BODY onLoad = "setClock()">
<FORM NAME="clocktext">
<INPUT TYPE="text" NAME="clock" VALUE="" SIZE=8>
</FORM>
</BODY>
</HTML>

To change the period of updating, currently set to 30 seconds, modify the last value in the setTimeout function. To change the update to 15 second intervals, have it read:

<![if !supportEmptyParas]> <![endif]>
setTimeout ("setClock()", 1000 * 15)

My clock also displays only the hour and minutes. You can display seconds, too, using the example script shown next. This script was originally authored by Brendan Eich (the developer of the JavaScript language) of Netscape. Because of its format and use of conditional expressions, it's a little harder to follow and change, but it's more compact than mine. You can chose which one you like better and implement it on your pages:

<![if !supportEmptyParas]> <![endif]>
<HTML>
<HEAD>
<TITLE>Clock Set</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function setClock() {
      var now = new Date();
      var Hours = now.getHours();
      var Minutes = now.getMinutes();
      var Seconds = now.getSeconds();
      var Value = "" + ((Hours >12) ? Hours - 12 : Hours)
      Value += ((Minutes < 10) ? ":0" : ":") + Minutes
      Value += ((Seconds < 10) ? ":0" : ":") + Seconds
      Value += (Hours >=12) ? " pm" : " am";
     document.clocktext.clock.value = Value;
      setTimeout ("setClock()", 1000);
}
</SCRIPT>
</HEAD>
<BODY onLoad = "setClock()">
<FORM NAME="clocktext">
<INPUT TYPE="text" NAME="clock" VALUE="" SIZE=11>
</FORM>
</BODY>
</HTML>

Display the Document Source/Document Info windows

A handy feature of Netscape is the "View, Document Source" and "View, Document Info" commands.

1 2 Page 1
Page 1 of 2