JavaScript FAQ

This FAQ is a work in progress by Andy Augustine. If there is a topic that you think should be added to the list, post it to one of the following groups and I will add it. Listed here are a collection of answers, hacks, workarounds, and kludges that have been taken from the:

Other than JavaScript 411, links to a variety of JavaScript pages on the Web can be found at Andrew Wooldridge's JavaScript Index site. If you have found your way here, I assume that you've already tried to find the information you need from Netscape's Official JavaScript Docs. They have been working hard lately to update their docs and have even posted the entire JavaScript guide in zipped format for offline viewing. I highly recommend that you get it now because when its finished there might be a charge for it in book form.


SECTION I. Some basics you must know before proceeding! SECTION II. Known Bugs and Workarounds SECTION III. Dealing with Forms SECTION IV. Frames and Windows SECTION V. Using arrays SECTION VI. Advanced Topics


SECTION I. JavaScript Basics before you start

There are several things about JavaScript that seem to slip past most newbies. Either they aren't documented correctly, or they are documented but just not where you'd think to look for them. Before you post a question to one of the groups above, you should consult the 'Known Bugs' list for your operating systems version of Netscape 2.0. In Windows you can find it in the Help menu under Release Notes. (On the Mac you can pull it down from the '?' menu.) If you've looked elsewhere and can't find the answer you need, read on!

HEIGHT and WIDTH tags for images
There's been a ton of people posting about having problems with their forms and JavaScript errors. Once you make the decision to start writing JavaScript code, you'd better get in the habit of using <HEIGHT> and <WIDTH> tags within all your inline images! An alternative fix that has been mentioned is adding an empty <SCRIPT> </SCRIPT> tag to the bottom of your HTML, but as far as I'm concerned the image tags have an added benefit in performance. They will make the browser load your document with placeholders for the images so that it can give the user something to look at while your pics load.


Where does the SCRIPT go in my HTML?
The safest place to put your <SCRIPT LANGUAGE="JavaScript"></SCRIPT> tags is within the <HEAD>. This will force it to be loaded into the browser's memory first. If you put code anywhere else there's always a chance that a user might click on an image or link before your code is fully loaded, resulting in chaos and errors. Here's a quick look:
    ----------
    <HTML>
    <HEAD>
    <TITLE>Example</TITLE>

    <SCRIPT LANGUAGE="JavaScript">
    <!-- HIDE FROM OLD BROWSERS

    code goes here

    // --> STOP HIDING
    </SCRIPT>
    </HEAD>

    <BODY>
    HTML goes here
    </BODY> </HTML> 
    ------------


How do I load a JavaScript library without embedding it in my HTML?
This feature is one of those that never made the Netscape Navigator 2.0 release. In 2.1 you will (hopefully) be able to save your scripts in a file with a xxx.js extension and then call them remotely from any of your web pages. This will be a very nice addition.


How do I print a frame generated by JavaScript?
Currently it is not possible to print any data (html,text,...) generated by JavaScript code. Another print-related problem with 2.0 is that if you print a page with a form on it, the form will show up but the user input will not.


How do I define a variable as global/local?
[Answer: Brendan Eich]
In Netscape 2.0, there are bugs to do with implicitly defining a global variable by setting a new name with assignment within a function. Example:
    function f() { x = 3; ... }
                   ^^^^^
where x is unbound when f's definition is parsed. The bugs may lead to wrong answers, but should not crash you (I think).

You should say what you mean here. If the intent is for x to be local, you must use var before it. To avoid trouble, you may choose a style where you always use 'var' to introduce new variables whereever you need them. If you are writing a function that wants local variables (or needs them, if it is recursive), use var. If you want to use a global in a function, make sure there is a top-level var statement that introduces the global before the function definition:

    <SCRIPT LANGAUGE="Javascript">
    <!-- hide from old browsers

    var x ...

    function f() { x = 3; var local = ... }

    // done hiding -->
    </SCRIPT>


How do I use the <APPLET> tag?
This tag is used by the Java programming language, which is separate from Javascipt. Sun and Netscape are currently working together so that in the future, code written in one language will be able to reference code written in the other. This is not yet implemented. If you're looking for information on Java, try http://java.sun.com.

If you're looking to call a JavaScript function from within a Java Applet, you can use this call (submitted by Achille Hui):

    showDocument("javascript:/**/myJSfunction()"
It appears that the /**/ is necessary to call 'myJSfunction()' instead of '/myJSfunction'. If you're interested in how Javascript reference Java in the future (Navigator 2.1), Brendan Eich wrote:
Statement of work in progress for 2.1:

You will be able to get and set Java public static fields as if they were
JavaScript properties of an object named after the package-qualified class
name, and call Java methods that are public, provided you can reach their
instances from the top-level Applet context thing.

In JavaScript, you name an applet via either document.applets[myAppletIndex]
or document.myApplet where a NAME attribute has been used.

The reflection of public fields and methods from Java into JavaScript will
be automatic and lazy.


Can I do animations with Javascript?
No, you cannot redraw only part of a page, although there are some other ways to do this. If you would like to run an animation, here are some basic suggestions:


[ Back to top ]

SECTION II. Known Bugs and Workarounds

Although JavaScript development has come a long way in a short time, there are still a few glitches that can tie up your projects if you're unaware of them. Some of these bugs only occur on one platform. However if your system is not affected by one of those listed below, you must keep in mind that everyone viewing your pages with the afflicted platform will run into difficulties and possibly even crash. You should try and familiarize yourself with all of the problems below to make sure you're not writing buggy code.

Why do long strings generate the 'Unterminated String Literal' message?
The exact reason why this happens is unclear, but the fix is easy. If the following string was causing problems in your code:
    var mystr="This is an example of a very long sting that is just like a run-on sentence
           and may break the code.  Somebody suggested theres a 254 character limit for 
           Windows 3.1 so this example is an attempt to be at least that long.  I don't
           know who would simply define a string this long, but there are times when it's
           necessary."
you should break it into smaller peices on sepeareate lines using the + sign to concatenate it. The fix would look like this:
    var mystr="This is an example of a very long sting that is just like a run-on sentence"
           + "and may break the code.  Somebody suggested theres a 254 character limit for"
           + "Windows 3.1 so this example is an attempt to be at least that long.  I don't"
           + "know who would simply define a string this long, but there are times when it's"
           + "necessary."


I pass a variable to the parent/sibling frame, and it's fine. But when the passing frame unloads, the value gets corrupted. What's the fix?
[Answer: Bill Dortch]
    ** parent **
    var myvar = ""
    function setvar (value) {
      myvar = "" + value; // create new string in parent context
    }
  
    ** child **
    parent.setvar("myvalue");


Eval() crashes Navigator on Windows 3.11 in 2.0b6 or later.
[Answer: Bill Dortch]
No direct fix. Examine navigator.appVersion to determine if user is Win16, and either don't load the offending code, or branch around it. EXAMPLE:
    if (navigator.appVersion.indexOf("Win16") == -1) { // not Win16
      eval (...); // evil!!!
    }
    else 
      doSomethingElse();


When I call window.open(), a new window is created but it's empty.
In Netscape Navigator 2.0 (MAC and X versions) the URL that is passed to window.open() fails to load. The following workaround will work:
    var newWin = window.open(myURL,'myWin')
    if (navigator.appVersion.indexOf("(X11") != -1 ||
        navigator.appVersion.indexOf("(Mac") != -1)
      newWin = window.open(myURL,'myWin')
The trick here is to call window.open() a second time to force the load.


On some X platforms, boolean options for a new window may be ignored.
It is valid to specify options for a new window by using: 'toolbar=yes', 'toolbar=1', or 'toolbar'. However, there is a X-platform-specific bug that may ignore these options no matter how you turn them on. This is a bug on X only, and it will be fixed in Navigator 2.1.


Why is my array of radio buttons indexed in reverse order?
When you create a set of radio buttons, you expect them to be placed into an array in order of creation. But if you've tried to access them, you've probably noticed that they were in reverse order. A simple fix for this is to assign an empty event handler to each radio object like this:
    <FORM NAME="radioTest">
     <INPUT TYPE="radio" NAME="testset" VALUE="A" onClick="">A
     <INPUT TYPE="radio" NAME="testset" VALUE="B" onClick="">B
     <INPUT TYPE="radio" NAME="testset" VALUE="C" onClick="">C
    </FORM>
Here's proof that it works:
A B C

[ Back to top ]

SECTION III. Dealing with Forms


RELOAD button: how do I make a button that will reload the current document?
You can make force the current page to reload by using assigning the function below to the onClick method of a button or link like this: funtion reloadIt() { location = '#' } ... <FORM><INPUT TYPE="button" VALUE="Reload" onClick="reloadIt()"></FORM> Also look at the Back button.


When I use myRadio.value, the value is always <undefined>.
Try myRadio[i].value for i in [0,numRadioButtons] -- because HTML says that radio-buttons all have the same NAME attribute, they reflect as an array of button objects.


How do I cancel the submission of a form if the user input was invalid?
If you have a form that you would like to validate before submitting (and cancel submission if its invalid), then you would assign the form's onSubmit event handler to call your validation function. The important part is that in order to cancel the submission, your function would have to return false and the form would have to be declared as follows:
    function validate() {
     if (**test for valid input**)
      return true
     else return false
    }
    ...
    <FORM onSubmit="return validate()">
NOTE: you do not return false from the SUBMIT button's onClick handler! The former is sufficient and relieves you from having to write N onClick handlers if your form has N submit buttons -- you write an onSubmit handler once in the <form ...> tag.


How can I control the size of the buttons I create?
The customizing of buttons is very limited at present. There are no specific button attributes that can manipulate the way in which they are drawn. The only can to adjust a button's length is to change the text within it. Adding spaces or shortening phrases should do the trick.
  <INPUT TYPE="button" VALUE="Without spaces">
  

  <INPUT TYPE="button" VALUE="       Button with spaces       ">
  


[ Back to top ]

SECTION IV. Frames and Windows

One of the most dynamic uses of JavaScript is in conjunction with Frames. You can make cross-frame calls to functions/objects/variables in separate frames by simply calling something like the following:
    parent.myframe.myobj
    parent.myframe.myfunction(mylocalvariable)
Note that when you call a function in another frame, the scope of the parameters that are passed is local to the calling frame. If you want to call a function on a element in another frame, you could use something like:
    mylocalfunction(parent.otherframe.myvariable)
    parent.otherframe.myfunction(parent.otherframe.myvariable)
and explicitly declare which frames you are referencing.


BACK button: how does one frame make the other go back a page?
This is a simple task. Let's suppose you have two frames defined as follows:
    <FRAMESET COLSPAN="50,*">
     <FRAME SRC="navigationbar.html" name="nav" NORESIZE>
     <FRAME SRC="mainframe.html" name="info">
    </FRAMESET>

Then you could put this code in your navigationbar.html page to manipulate the info frame:
    <FORM NAME="buttonbar">
     <INPUT TYPE="button" VALUE="Go Back" onClick="parent.info.history.back()">
     <INPUT TYPE="button" VALUE="Go Home" onClick="parent.info.loaction="home.html">
     <INPUT TYPE="button" VALUE="Go Next" onCLick="parent.info.history.forward()">
    </FORM>

Alternatively, you could use the history.go(-1) and history.go(1) functions, as stated in the Netscape docs. Also look at the Reload button


What is the best way to synchronize the loading of frames
in order to avoid JavaScript error messages?

[Answer: Brendan Eich]
Sure, you can synch framed JavaScript execution to start only when the
whole frameset is loaded, but you have to write some JavaScript to do it.

In the top-most FRAMESET's ONLOAD handler, you can set a variable or
property of that window ("self.loadDone = true").  In all descendent
frame documents, you can make their first SCRIPT tag (or if there are no
SCRIPT tags only event handlers, in their BODY or FRAMESET tag's ONLOAD
handler) call the following function:

    function topWait(expr) {
       if (!top.loadDone) {
         // XXX expr had better not contain unescaped single quotes!
         setTimeout("topWait('" + expr + "')", 500)
       } else {
         eval(expr)
       }
     }

to do whatever work (expr, a string containing JavaScript code, most likely a
call to the "main" function for that document) needs to be done only
after the whole frame tree is loaded.

There are more complicated schemes that involve code in different frame
documents being very careful to test (parent.otherframe.forms != null &&
parent.otherframe.forms.length == 2), e.g., and not look for properties
or members of such object references until the test succeeds.


I've used window.open() to create a new window.
How do I reference my original window from the new one?
The method thats I've adopted to do this defines a new property for the window object that you can create in the following manner:
    var popWindow = window.open(myUrl,'myWindow')
    popWindow.creator = self
Now you can reference the original window and all its properties/functions/... from 'myWindow' with standard Javascipt syntax:
    ***code goes in popWindow's source***
    creator.document.myform.myfield.value = aNewValue;
Be sure you're aware of the known bug with window.open().


I've got a page that uses frames, how do I make a link that will come up in the whole window, erasing the frames?
If you've used the <FRAMESET> tag to create a framed web page, it is simple to have any of the links come up in the entire window. To erase the frames and utilize the entire window, try this:
    <A HREF="mypage.html"" TARGET="_top>Go to my non-framed page</A>


[ Back to top ]

SECTION V. Using arrays


How do I create/initialize an array in Javascript?
[Answer: Brendan Eich]
Here's an array constructor that sets the array element properties from its arguments:
    function initArray() {
      this.length = initArray.arguments.length
      for (var i = 0; i < this.length; i++)
        this[i+1] = initArray.arguments[i]
    }

    var a = new initArray(1, true, "three")

This would create an array 'a' with the following properties:
    a.length = 3
    a[1] = 1
    a[2] = true
    a[3] = three


[ Back to top ]

SECTION VI. Advanced Topics

This section will deal with concepts like efficient memory usage, arrays, and security problems to name a few.


What happens when I recursively call setTimeout()?
[Answer: Brendan Eich]
A recursive function is one that calls itself under given circumstances or within set bounds. With a setTimeout() call, you can have a function seed itself (repeat a process). The following short example shows this best. (NOTE: This function should not be used as is, because it does not provide a means of checking if clock() is already running, along with other hazardous quirks. If you want, look here for a working example.)
    function clock() {
     new_date = new Date()
     window.document.form1.f_clock.value = new_date.getSeconds()
     id = setTimeout("clock()",1000)
    }

    <BODY onLoad="clock()">
In 2.0, the quoted expressions passed to eval() and setTimeout() are compiled into bytecode and retained for the life of the current document. So if you use setTimeout to arm another timeout, your application will bloat navigator over time. This bug will be fixed in 2.1.


How do I detect if a user has a certain plug-in?
[Answer: Brendan Eich]
Major plugin support is coming in 2.1, but in the mean time,
you can use this function to test for equipped plugins:

    function probePlugIn(mimeType) {
      var havePlugIn = false
      var tiny = window.open("", "teensy", "width=1,height=1")
      if (tiny != null) {
        if (tiny.document.open(mimeType) != null)
          havePlugIn = true
        tiny.close()
      }
      return havePlugIn
    }

    var haveShockWavePlugIn = probePlugIn("application/x-director")

/be
NOTE: this suggestion will cause the client to be prompted (whether to 'Pick an App', 'Save', or 'Cancel') if they do not have the plug-in. This message was posted as a means of reference for others to think about.


Back to top ][ Comments to Andy Augustine

Visitor #3539
© 1996 Frequency Graphics