Alternate comp.lang.javascript FAQ

Version 33.0, Updated 2013-11-06, by The FAQ Maintenace Team.

4 Functions

4.1 What is (function(){ /.../ })() ?

This is an anonymous FunctionExpression that is called immediately after creation.

Variables declared inside a function are not accessible from outside the function. This can be useful, for example, to hide implementation details or to avoid polluting the global scope.

4.2 What is a function statement?

The term function statement has been widely and wrongly used to describe a FunctionDeclaration. This is misleading because in ECMAScript, a FunctionDeclaration is not a Statement; there are places in a program where a Statement is permitted but a FunctionDeclaration is not. To add to this confusion, some implementations, notably Mozillas', provide a syntax extension called function statement. This is allowed under section 16 of ECMA-262, Editions 3 and 5.

Example of nonstandard function statement:

 // Nonstandard syntax, found in GMail source code. DO NOT USE. 
 try { 
   // FunctionDeclaration not allowed in Block. 
   function Fze(b,a){return b.unselectable=a} 
   /*...*/ 
 } catch(e) { _DumpException(e) } 

Code that uses function statement has three known interpretations. Some implementations process Fze as a Statement, in order. Others, including JScript, evaluate Fze upon entering the execution context that it appears in. Yet others, notably DMDScript and default configuration of BESEN, throw a SyntaxError.

For consistent behavior across implementations, do not use function statement; use either FunctionExpression or FunctionDeclaration instead.

Example of FunctionExpression (valid):

 var Fze; 
 try { 
   Fze = function(b,a){return b.unselectable=a}; 
   /*...*/ 
 } catch(e) { _DumpException(e) } 

Example of FunctionDeclaration (valid):

 // Program code 
 function aa(b,a){return b.unselectable=a} 

5 Dates

ISO 8601 defines date and time formats. Some benefits include:

For an event with an offset from UTC, use YYYY-MM-DDThh:mm:ss±hh:mm.

Never use a local date/time format for a non-local event. Instead, use UTC, as in YYYY-MM-DDThh:mm:ssZ (Z is the only letter suffix).

The T can be omitted where that would not cause ambiguity. For rfc 3339 compliance, it may be replaced by a space and for SQL, it must be replaced by a single space.

Year 0000 is unrecognized by some formats (XML Schema, xs:date).

5.1 How do I format a Date object with javascript?

A local Date object where 0 <= year <= 9999 can be formatted to a common ISO 8601 format YYYY-MM-DD with:-

 /** Formats a Date to YYYY-MM-DD (local time), compatible with both 
 *  ISO 8601 and ISO/IEC 9075-2:2003 (E) (SQL 'date' type). 
 *  @param {Date} dateInRange year 0000 to 9999. 
 *  @throws {RangeError} if the year is not in range 
 */ 
 function formatDate(dateInRange) { 
   var year = dateInRange.getFullYear(), 
     isInRange = year >= 0 && year <= 9999, yyyy, mm, dd; 
   if(!isInRange) { 
     throw RangeError("formatDate: year must be 0000-9999"); 
   } 
   yyyy = ("000" + year).slice(-4); 
   mm = ("0" + (dateInRange.getMonth() + 1)).slice(-2); 
   dd = ("0" + (dateInRange.getDate())).slice(-2); 
   return yyyy + "-" + mm + "-" + dd; 
 } 

5.2 How can I create a Date object from a String?

An Extended ISO 8601 local Date format YYYY-MM-DD can be parsed to a Date with the following:-

 /**Parses string formatted as YYYY-MM-DD to a Date object. 
 * If the supplied string does not match the format, an 
 * invalid Date (value NaN) is returned. 
 * @param {string} dateStringInRange format YYYY-MM-DD, with year in 
 *        range of 0000-9999, inclusive. 
 * @return {Date} Date object representing the string. 
 */ 
 function parseISO8601(dateStringInRange) { 
   var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/, 
      date = new Date(NaN), month, 
      parts = isoExp.exec(dateStringInRange); 

   if(parts) { 
     month = +parts[2]; 
     date.setFullYear(parts[1], month - 1, parts[3]); 
     if(month != date.getMonth() + 1) { 
       date.setTime(NaN); 
     } 
   } 
   return date; 
 } 

10 Windows and Frames

The window object (also referred to by self) is "DOM Level 0". No formal standard for it exists.

10.1 How can I disable the back button in a web browser?

You can't. The browser's history cannot be modified. However, you can use self.location.replace(url); in some browsers to replace the current page in the history.

10.2 How do I access a frame's content?

To reference another frame on the same domain:

The content window of a FRAME or IFRAME can be accessed by the frames collection.

Example:

var fwin; 
fwin = self.frames[0]; // or: 
fwin = self.frames["iframeName"]; 

or, from the IFRAME or FRAME element:

var iframeEl = document.getElementById("myFrame"); 
// Nonstandard, but widely supported.
var fwin = iframeEl.contentWindow; 
// DOM2 HTML Standard. 
var fdoc = iframeEl.contentDocument; 

A global identifier moomin in the the iframe's content window is accessed as fwin.moomin.

To communicate between frames on different domains:

Where supported, (IE8, Firefox 3, Opera 9, Safari 4), use window.postMessage( message[, port], otherDomain);.

Example: http://jibbering.com/faq/example/postMessage.html

Where window.postMessage is not supported, the window.name property can be set on the other window, which can poll for updates to that property using setInterval(checkWinName, 100); where checkWinName is a function that polls to check the value of self.name.

10.3 How do I find the size of the window/browser canvas area?

While it is often asked about window size, what is more relevant is the "canvas area" of the browser.

Where supported in NN: (>NN4.0)

var winWidth = window.innerWidth; 
var winHeight = window.innerHeight; 

Where supported in IE: (>IE4.0)

var winWidth = document.body.clientWidth; 
var winHeight = document.body.clientHeight; 

Where supported in modern browsers:

var winWidth = document.documentElement.clientWidth; 
var winHeight = document.documentElement.clientHeight; 

Where supported in DOM compliant browsers:

var winWidth, winHeight, d=document; 
if (typeof window.innerWidth!='undefined') { 
  winWidth = window.innerWidth; 
  winHeight = window.innerHeight; 
} else { 
  if (d.documentElement && 
    typeof d.documentElement.clientWidth!='undefined' && 
    d.documentElement.clientWidth!==0) { 
      winWidth = d.documentElement.clientWidth; 
      winHeight = d.documentElement.clientHeight; 
  } else { 
    if (d.body && typeof d.body.clientWidth!='undefined') {
      winWidth = d.body.clientWidth; 
      winHeight = d.body.clientHeight; 
    } 
  } 
}

Note: The dimensions can not be determined accurately until after the document has finished loading.

10.4 How do I check to see if a child window is open, before opening another?

var myWin;
function openWin(aURL) {
  if (!myWin || myWin.closed ) {
    myWin = window.open(aURL,'myWin');
  } else {
    myWin.location.href = aURL;
    myWin.focus();
  }
}

Popup windows cause usability problems and are generally best avoided.

10.5 Why does framename.print() not print the correct frame in IE?

IE prints the frame that has focus when you call the print method frameref.focus();frameref.print();

10.6 How do I close a window and why does it not work on the first one?

Use windowRef.close(), where windowRef is a window object reference, such as window, top, parent, self, or a reference obtained from the window.open() method. You can only close windows opened by scripts, no others.

10.7 Why do I get permission denied when accessing a frame/window?

In the normal browser security model, a script may only access the properties of documents served from the same domain or IP address, protocol, and port.

Any attempt to access a property in such cases will result in a "Permission Denied" error. Signed scripts or trusted ActiveX objects can overcome this in limited situations.

10.8 How do I make a 10 second delay?

There is no built-in way to pause execution in javascript such as a sleep function, but hosts usually provide a method of some form. Web browsers are designed for event driven programming and only provide the setTimeout and setInterval functions to facilitate timed delays. The delay before calling getSnork may exceed the second parameter to setTimeout and setInterval due to implementation differences among browsers.

To call the function getSnork, approximately 10 seconds after the function getMoomin() completes, you would do this:

getMoomin();
setTimeout(getSnork, 10000);

Script execution is not stopped, and adding getSnufkin() after the setTimeout line would immediately execute the function getSnufkin before getSnork.

Achieving delays through running a loop of some sort for a pre-defined period is a bad strategy, as that will inhibit whatever was supposed to be happening during the delay, including blocking user interation.

Other (less event driven) hosts have different wait functions, such as WScript.Sleep() in the Windows Script Host.

10.9 How do I change print settings for window.print()?

In a normal security environment, you can't change anything.

Print Stylesheet rules provide options.

For IE, ActiveX or Plugin ScriptX and Neptune from Meadroid to give you more control for Windows versions of Internet Explorer, Netscape, and Opera.

10.10 How do I change the confirm box to say yes/no or default to cancel?

The buttons on a confirm box cannot be changed, nor can a default button be specified.

Change the question to a statement so that "OK" is suitable as the default response.

Example:

10.11 How do I prompt a "Save As" dialog for an accepted mime type?

It is not possible with client-side javascript.

Some browsers accept the Content-Disposition header, but this must be added by the server. Taking the form:- Content-Disposition: attachment; filename=filename.ext

10.12 How do I modify the current browser window?

In a default security environment you are very limited in how much you can modify the current browser window. You can use window.resizeTo or window.moveTo to resize or move a window respectively, but that is it. Normally you can only suggest chrome changes in a window.open.

10.13 How do I POST a form to a new window?

Use the target attribute on the form, opening a window with that name and your feature string in the onsubmit handler of the FORM.

<form action="" 
      method="post"
      target="wndname" 
      onsubmit="window.open('',this.target);return true;"
>

10.14 How do I open a new window with javascript?

New windows can be opened on browsers that support the window.open function and are not subject to the action of any pop-up blocking mechanism with code such as:-

var wRef;
if (window.open) {
  wRef = window.open("http://example.com/page.html","windowName");
}

Other FAQ Resources: