comp.lang.javascript FAQ - 9.65 - 2007-03-04

1 meta-FAQ meta-questions

2 comp.lang.javascript tips

2.1 Which newsgroups deal with javascript?
2.2 What questions are off-topic for clj?
2.3 What do I have to do before posting to clj?
2.4 Why was my post not answered?
2.5 How do I direct someone to this FAQ?
2.6 What is ECMAScript?
2.7 What is JScript?
2.8 What are object models?
2.9 What is the document object model?
2.10 Internationalization and Multinationalization in javascript.
2.11 I have a question that is not answered in here or in any of the resources mentioned here but I'm sure it has been answered in clj. Where are the clj archives located?
2.12 What does the future hold for ECMAScript?

3 javascript resources

3.1 What books cover javascript?
3.2 What online resources are available?

4 Quick Answers

4.1 How do I protect my javascript code?
4.2 How can I disable the back button in a web browser?
4.3 How can I access the client-side filesystem?
4.4 How can I see in javascript if a web browser accepts cookies?
4.5 How can I prevent access to a web page by using javascript?
4.6 How do I convert a Number into a String with exactly 2 decimal places?
4.7 Why does 5 * 1.015 != 5.075 or 0.06+0.01 != 0.07?
4.8 How do I communicate between frames in a web browser?
4.9 How do I find the size of the window/browser canvas area?
4.10 How do I check to see if a childwindow is open, before opening another?
4.11 Why does framename.print() not print the correct frame in IE?
4.12 Why does K = parseInt('09') set K to 0?
4.13 How do I get the value of a form control?
4.14 How do I close a window and why does it not work on the first one?
4.15 How do I modify the current page in a browser?
4.16 How do I trim whitespace - LTRIM/RTRIM/TRIM?
4.17 How do I force a reload from the server/prevent caching?
4.18 How do I get a perl/asp/php variable into client-side js?
4.19 Why do I get permission denied when accessing a frame/window?
4.20 How do I make a 10 second delay?
4.21 Why does 1+1 equal 11? or How do I convert a string to a number?
4.22 How do I generate a random integer from 1 to N?
4.23 How do I change print settings with window.print()?
4.24 I have <a class="javascript:somefunction()"> what ... ?
4.25 My element is named myselect[] , how do I access it?
4.26 How do I detect Opera/Netscape/IE?
4.27 How do I disable the right mouse button?
4.28 How do I change the confirm box to say yes/no or default to cancel?
4.29 How do I log-out a user when they leave my site?
4.30 How do I format the Last-Modified date with javascript?
4.31 Why are my rollovers so slow?
4.32 How do I change the text in the url/location bar?
4.33 How do I prompt a "Save As" dialog for an accepted mime type?
4.34 How do I run a server side script?
4.35 I have window.status="Moomin"; why doesn't the statusbar change?
4.36 How do I modify the current browser window?
4.37 How do I POST a form to a new window?
4.38 How do I download a page to a variable?
4.39 How do I access a property of an object using a string?
4.40 When should I use eval?
4.41 Why doesn't the global variable "divId" always refer to the element with id="divId"?
4.42 How do I open a new window with javascript?
4.43 How do I get my browser to report javascript errors?
4.44 What is AJAX?

5 Comments and Suggestions

5.1 Why do some posts have <FAQENTRY> in them ?
5.2 How do I make a suggestion?

1 meta-FAQ meta-questions

You are reading the comp.lang.javascript meta-FAQ, version 9.65. It is available on the web at www.jibbering.com/faq/index.html in HTML form.

This is the official comp.lang.javascript (clj) FAQ. Or, more accurately, the meta-FAQ. It mainly provides URLs to further information about javascript, and some hints and tips to make your stay in comp.lang.javascript more enjoyable.

This document was created for three reasons: to help reduce the high levels of noise on clj, to provide a resource for people new to javascript, and to point to locations that contain valuable javascript resources.

The FAQ is currently posted one section daily for review, questions and a reminder that the FAQ is available.

To cope with a desire for additional explanation and detail relating to some aspects of the FAQ, an additional resource is available at:- www.jibbering.com/faq/faq_notes/faq_notes.html It has been provided separately to avoid increasing the size of the FAQ to a point where it would be unreasonable to post it to the group.

Conventions used in the HTML version.

If your browser supports CSS, and follows our Suggestions, we use these conventions to denote various things:

Pages linked to from within a blue dashed line were updated since the last publication of the comp.lang.javascript FAQ (2007-03-04). Links contained in a red dotted line were unavailable at the time of publication.

Boxes with a light blue background contain links to more information on the question discussed. Code samples are given in a yellow background.

2 comp.lang.javascript tips

2.1 Which newsgroups deal with javascript?

The official Usenet newsgroup dealing with javascript is comp.lang.javascript . There are other newsgroups but many of them are not carried by most news feeds. clj is an unmoderated newsgroup.

2.2 What questions are off-topic for clj?

The comp.lang.javascript newsgroup deals with ECMAScript languages, so any questions about JavaScript or JScript are welcome. However, the majority of questions sent to this group relates to javascript in a web browser. If you are experiencing issues with a particular browser, or the host is not a browser at all, please make this information clear.

Javascript and Java are two completely different languages. Java questions should be asked in one of the comp.lang.java.* newsgroups; they are not appropriate for clj (as Java and javascript are distinct programming languages with only superficial similarities due to sharing a C-like syntax and some of the characters in their names).

Questions dealing with other scripting languages, such as VBScript, PerlScript or CGI scripting are also off-topic, as are HTML-only or CSS-only questions.

Questions that are specific to Microsoft's JScript may also be appropriately asked at: microsoft.public.scripting.jscript

The comp.lang.javascript newsgroup charter is included in www.jibbering.com/faq/faq_notes/cljs_charter.html

2.3 What do I have to do before posting to clj?

Before posting to clj, you should thoroughly read this document. You should also check the resources mentioned in section 3 and the Quick Answers in section 4. Read FYI28/RFC1855 www.ietf.org/rfc/rfc1855.txt on Usenet and www.jibbering.com/faq/faq_notes/clj_posts.html . Also you should read all appropriate posts to the clj newsgroup for several days. Most questions come up at least once every other day and people can get annoyed of answering them repeatedly.

Please state your question as clearly and concisely as possible, as this will make it far easier for the other readers of the group to understand your problems and suggest possible solutions. Use the Subject: of your post to indicate the type of problem you have, but include the question in the body as well. 'Help!' or 'I hate Netscape!' are not nearly as useful to contributors who do not read every post as 'parseInt("09")!=9'.

Has the same question already been posted that day? - if it has wait to see if the answers to that solve your problem.

Include the script you have been working on (or URL) - indicate the problem spots and/or previous attempts. Try to limit the length of your post by removing extraneous page elements, but avoid removing script unless you are sure it is not an issue. If the script is long though, please do not post the full script and just provide a link. As a guide more than 500 lines for a post is not normally a good idea in any circumstances. A mention of which platforms and browsers are used or are giving problems is also necessary.

Post in plain-text only. Do not post using HTML. If you have to include your script, paste it in to your post in plain-text. Do not uuencode it or attach it using MIME. There is good reason for this request: many newsreaders do not read HTML or MIME, and this limits the number of people who could help you. Test posts belong in test newsgroups (they have "test" in their names). Make sure your code is executable as transmitted. Use line breaks to keep the posting agent from wrapping code incorrectly.

When replying to a message on the group quote the minimum of the preceding messages that is sufficient to provide context for the reply but trim the remainder, and add your comments below the pertinent section of quoted material, as per FYI28/RFC1855 (never top post).

Don't ask, or at least expect, to be emailed individually. Some individuals run scams for the purpose of collecting active email addresses and many won't risk being victimized. If you have circumstances that won't allow you to read clj for the follow-up, explain what they are and ask to be CC'ed a copy. You also might try groups.google.com/group/comp.lang.javascript/topics to read replies.

Don't expect to be able to e-mail contributors to the group privately. E-mail addresses are often obscured, fictional or unmonitored spam sinks (this is an increasingly normal (and even unofficially recommended) practice as open e-mail addresses in news articles will be both the target of spam and used as fake sender's addresses in spam to third parties).

Don't take flames too seriously, and don't start a thread complaining about rude or flippant responses. There is already enough noise in clj. Keep a sense of humour while posting and reading and everything will be a lot more enjoyable.

Remember that it is not the job of posters here to help you. The majority of regular posters here do so voluntarily in their free time. They have good days and bad days just like everyone else.

clj is a technical group: the posting of job adverts and commercial adverts are not welcome. Job postings should go to an appropriate regional jobs group. Announcements of products of particular relevance to javascript are welcome, but not more often than once per major release, and then post a short link to the product's webpage.

Please do not post copyrighted material to clj without permission from the copyright holder.

2.4 Why was my post not answered?

This could be for several reasons:

If it is not one of these, then after a few days consider reposting after checking groups.google.com/group/comp.lang.javascript/topics for replies. Make sure the post is phrased well, and everything needed to answer is correct, and the subject is appropriate.

2.5 How do I direct someone to this FAQ?

This document is posted to clj very frequently. There should be no reason to direct someone to it. However, if someone asks a question answered in this FAQ or in one of the resources listed herein, please let them know their question is answered in the FAQ and that the FAQ can be found at www.jibbering.com/faq/

2.6 What is ECMAScript?

www.ecma-international.org/publications/standards/Ecma-262.htm ECMAScript is the international standard for javascript. JScript 3.0 and JavaScript 1.2 (available with version 4. browsers) are more or less ECMAScript compliant. In addition ECMA 327 defines the Compact Profile of ECMAScript by describing the features from ECMA 262 that may be omitted in some resource-constrained environments. Note that ECMAScript did not attempt to standardize the document object model.

The current edition is ECMA-262, 3rd Edition. There is some support for this edition in JScript 5.0 and JavaScript 1.3. JScript 5.5 and JavaScript 1.5, in Netscape 6.1 and later, are compliant (JavaScript 1.5 in Netscape 6 missed some methods).

2.7 What is JScript?

JScript is Microsoft's implementation of ECMAScript.

Questions that are specific to Microsoft's JScript may also be appropriately asked at: microsoft.public.scripting.jscript

2.8 What are object models?

Object models (OMs) are not part of the javascript language: they are provided by the host to allow javascript (or other scripting language) to communicate with the host. An object model may allow javascript to access a file system, or control a nuclear power station. The most commonly used object models via javascript are provided by Active Server Pages, Server Side JavaScript, and the Windows Script Host. The most common of all of course is the Document Object Model (DOM) provided by web browsers. Other document types such as SVG also define scriptable DOMs, mostly as extensions of the W3C Core DOM specification designed for use with XML documnets.

2.9 What is the document object model?

This is the collection of objects provided by each browser. Basically, any object in the window hierarchy is part of the DOM. This means that document.writeln(), for example, is not a javascript method but is, in fact, a method provided by the DOM. The DOM has been standardised by the World Wide Web Consortium (W3C); however, like all W3C standards, browser support is not yet complete. Most cross-browser coding problems come from slightly different implementations of the DOM in the differentbrowsers. W3 DOM FAQ www.w3.org/DOM/faq.html

The W3C has worked on three versions of the DOM to date. The third version has not yet achieved the status of a recommendation www.w3.org/DOM/ .

2.10 Internationalization and Multinationalization in javascript.

Internationalization means using one form which is both acceptable and understood everywhere. By default, javascript has no such features; but if an international standard exists it can be coded for.

For example, there is an international standard for numeric Gregorian date format; but there is none for decimal and thousands separators.

Multinationalization means using different forms for different nations. It cannot work well in general, because it requires a knowledge of all national preferences and the ability to choose the right one, in an environment where many systems are inappropriately set anyway.

JavaScript has a few Multinationalisation features. The various toString() methods are all implementation dependent, but tend to use either UK or US settings (not necessarily correctly). ECMAScript Ed. 3 introduced some capabilities, including the toLocaleString() method which should create a string based on the host's locale.

Much more support is expected in future versions of JavaScript.

2.11 I have a question that is not answered in here or in any of the resources mentioned here but I'm sure it has been answered in clj. Where are the clj archives located?

groups.google.com/group/comp.lang.javascript/topics Maintain an archive of comp.lang.javascript going back to 1996 and provide diverse archive searching facilities.

2.12 What does the future hold for ECMAScript?

The ECMAScript Technical Committee is now working on the fourth edition, the first implementation of which is JScript.NET. It includes a compiler, allowing you to create standalone JScript executables.

The fourth edition of ECMAScript will provide new features like typed variables, and classes. More information can be found at: www.mozilla.org/js/language/es4/index.html , msdn.microsoft.com/voices/scripting07142000.asp or from microsoft.public.dotnet.languages.jscript

3 javascript resources

3.1 What books cover javascript?

The only book currently endorsed by c.l.j. regulars is:

JavaScript: The Definitive Guide, 4th Edition By David Flanagan ISBN:0-596-00048-0

Also by David Flanagan: JavaScript Pocket Reference, 2nd Edition. ISBN 0-596-00411-7 for language and API reference alone.

www.oreilly.com/catalog/jscript4/
Errata:
www.oreilly.com/catalog/jscript4/errata/

The Fifth Edition has been released but has not been reviewed thoroughly enough to gain a full endorsement from the regulars of c.l.j.

JavaScript: The Definitive Guide, 5th Edition By David Flanagan ISBN:0-596-10199-6

www.oreilly.com/catalog/jscript5/
Errata:
www.oreilly.com/catalog/jscript5/errata/
Davaid Flanagan's Blog Site:
www.davidflanagan.com/

3.2 What online resources are available?

Javascript FAQ site, please check first:-
javascript.faqts.com/
Mozilla JavaScript 1.5 reference:-
developer.mozilla.org/en/docs/JavaScript
Index of Netscape 4 JavaScript docs online (These documents are no longer available form Netscape but are still reproduced by Sun Microsystems, Inc.):-
docs.sun.com/source/816-6408-10/
Index of Archived Netscape 4 JavaScript docs online and for download:-
devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/reference/
Online Gecko DOM Reference:-
developer.mozilla.org/en/docs/Gecko_DOM_Reference
Download:-
www.mozilla.org/docs/dom/domref.zip
Microsoft (D)HTML reference:-
msdn.microsoft.com/workshop/author/dhtml/reference/dhtml_reference_entry.asp
JScript reference and main Microsoft script site:-
msdn.microsoft.com/library/en-us/script56/html/1e9b3876-3d38-4fd8-8596-1bbfe2330aa9.asp
msdn.microsoft.com/scripting/
Opera Documentation:-
www.opera.com/docs/specs/#ecmascript
www.opera.com/docs/specs/js/
ICab's Inscript documentation:-
www.muchsoft.com/inscript/
Archived documentation for MSIE 3.x:-
members.tripod.com/~housten/download/
The official ECMAScript specification:-
www.ecma-international.org/publications/standards/Ecma-262.htm
Other versions of the ECMAScript specification:-
www.mozilla.org/js/language/
DOM level 1 ECMA script binding:-
www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
DOM HTML level 2 ECMA script binding:-
www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html
FESI - a free implementation of ECMAScript in Java:-
www.lugrin.ch/fesi/index.html
Frequently asked questions about source code obfuscation:-
jibbering.com/faq/obfuscate.html
Sites discussing Active Server Pages:-
www.15seconds.com/
www.4guysfromrolla.com/
www.aspfaq.com/
DHTML source code and tutorials:-
www.w3schools.com/
Sites focused on using Scripting to automate Windows:-
www.windows-script.com/
cwashington.netreach.net/
Microsoft's Windows Scripting Host (WSH) Newsgroup:-
microsoft.public.scripting.wsh
Microsoft's JScript Newsgroup:-
microsoft.public.scripting.jscript
Manipulating times, dates and the lastModified date and time in javascript:-
www.merlyn.demon.co.uk/js-dates.htm
Venkman - Mozilla Visual JS debugger:-
www.mozilla.org/projects/venkman/
Whitebeam Apache Module - Server Side Javascript in Apache;-
www.whitebeam.org/
Digital Mars DMD Script, console and MS Active Script implementation of ECMAScript, claimed to be faster than other implementations:-
www.digitalmars.com/dscript/
Microsoft Script Debugger Documentation:
msdn.microsoft.com/library/en-us/sdbug/Html/sdbug_1.asp

4 Quick Answers

4.1 How do I protect my javascript code?

With clientside Javascript you can't as your code is distributed in source form and is easily readable. With JScript, there is the Script Encoder (see MSDN), but this is nothing more than obfuscation. Disabling the right mouse button also does nothing to protect your script in a Web browser.

Your code is likely protected under copyright laws. See:
www.wipo.int/about-ip/en/copyright.html
webdesign.about.com/msubcopyright.htm

4.2 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 location.replace(url); in some browsers to replace the current page in the history.

msdn.microsoft.com/workshop/author/dhtml/reference/methods/replace.asp
docs.sun.com/source/816-6408-10/location.htm#1194240

4.3 How can I access the client-side filesystem?

Security means that by default you can't. In a more restricted environment, there are options. For example, using LiveConnect to connect to Java with Netscape, and using the FileSystemObject in IE. Check groups-beta.google.com/group/comp.lang.javascript/topics for previous posts on the subject.

msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/af4423b2-4ee8-41d6-a704-49926cd4d2e8.asp
www.javaworld.com/javaworld/jw-10-1998/jw-10-apptowin32.html

4.4 How can I see in javascript if a web browser accepts cookies?

Writing a cookie, reading it back and checking if it's the same.

www.w3schools.com/js/js_cookies.asp
Additional Notes:
www.jibbering.com/faq/faq_notes/cookies.html
www.ietf.org/rfc/rfc2965.txt
www.galasoft-lb.ch/myjavascript/consulting/2001012701/
www.cookiecentral.com/

4.5 How can I prevent access to a web page by using javascript?

In practice you can't. While you could create a suitable encryption system with a password in the page, the level of support you need to do this means it's always simpler to do it server-side. Anything that "protects" a page other than the current one is definitely flawed.

4.6 How do I convert a Number into a String with exactly 2 decimal places?

When formatting money for example, to format 6.57634 to 6.58, 6.5 to 6.50, and 6 to 6.00?

Rounding of x.xx5 is uncertain, as such numbers are not represented exactly. See section 4.7 for Rounding issues.

N = Math.round(N*100)/100 only converts N to a Number of value close to a multiple of 0.01; but document.write(N) does not give trailing zeroes.

ECMAScript Ed. 3.0 (JScript 5.5 [but buggy] and JavaScript 1.5) introduced N.toFixed, the main problem with this is the bugs in JScripts implementation.

Most implementations fail with certain numbers, for example 0.07. The following works successfully for M>0, N>0:

function Stretch(Q, L, c) { var S = Q
 if (c.length>0) while (S.length<L) { S = c+S }
 return S
}
function StrU(X, M, N) { // X>=0.0
 var T, S=new String(Math.round(X*Number("1e"+N)))
 if (S.search && S.search(/\D/)!=-1) { return ''+X }
 with (new String(Stretch(S, M+N, '0')))
 return substring(0, T=(length-N)) + '.' + substring(T)
}
function Sign(X) { return X<0 ? '-' : ''; }
function StrS(X, M, N) { return Sign(X)+StrU(Math.abs(X), M, N) }
Number.prototype.toFixed= function(n){ return StrS(this,1,n)};
www.merlyn.demon.co.uk/js-round.htm
msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/b5f03400-865e-4ab2-818c-f734c0f6d6f0.asp

4.7 Why does 5 * 1.015 != 5.075 or 0.06+0.01 != 0.07?

Javascript numbers are represented in binary as IEEE-754 (IEC 559) Doubles, with a resolution of 53 bits, giving an accuracy of 15-16 decimal digits; integers up to about 9e15 are precise, but few decimal fractions are. Given this, arithmetic is as exact as possible, but no more. Operations on integers are exact if the true result and all intermediates are integers within that range.

In particular, non-integer results should not normally be compared for equality; and non-integer computed results generally need rounding; see 4.6.

msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/c7a6bd3a-4b1c-4dbe-8505-106dbf483b41.asp

4.8 How do I communicate between frames in a web browser?

To reference another frame, you simply need to step through the frame hierarchy: parent is the page the frame is defined in, parent.framename is another frame in the same frameset. To access a variable called Moomin in a frame called Snork you would use parent.Snork.Moomin . To call the function Snufkin in that frame you would use parent.Snork.Snufkin() .

4.9 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;

When using IE6 with in CSS1Compat mode (i.e. with a Formal DOCTYPE):

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

Combined:

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.

msdn.microsoft.com/workshop/author/dhtml/reference/properties/clientWidth.asp
docs.sun.com/source/816-6408-10/window.htm#1202446
msdn.microsoft.com/workshop/author/om/measuring.asp

4.10 How do I check to see if a childwindow is open, before opening another?

var myWin=null;
function openWin(aURL) {
 if (!myWin || myWin.closed ) {
  myWin=window.open(aURL,'myWin');
 } else{
  myWin.location=aURL;
  myWin.focus();
 }
}
msdn.microsoft.com/workshop/author/dhtml/reference/properties/closed.asp
docs.sun.com/source/816-6408-10/window.htm#1201877

4.11 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();

msdn.microsoft.com/library/en-us/dnscrpt/html/dhtmlprint.asp

4.12 Why does K = parseInt('09') set K to 0?

The parseInt function decides what base to convert a number represented as a string to by looking at the string. It assumes that any string beginning with '0x' or '0X' represents a hexadecimal number, but it has a choice with a leading zero: the string could represent a number that can be either octal or decimal. Assuming octal, the string '09' will be converted to 0 (octal digits are 0-7); assuming decimal, '09' will be converted to 9 (the leading zero is ignored). To force use of a particular base, use the radix parameter: parseInt("09",base)

msdn.microsoft.com/library/en-us/script56/html/js56jsmthparseint.asp
docs.sun.com/source/816-6408-10/toplev.htm#1064173
www.jibbering.com/faq/faq_notes/faq_notes.html#FAQN4_12

4.13 How do I get the value of a form control?

In HTML documents, named forms may be referred to as named properties of the document.forms collection, and named form controls may be referred to as named properties of the form's elements collection:

var frm = document.forms["formname"];
var contrl = frm.elements["elementname"];

The (string) value property of such controls can be read directly from the element:-

var value = contrl.value;
var value = (+contrl.value); //string to number: see 4.21

Some exceptions would be:

First Exception: Where the control is a SELECT element, and support for older browsers, such as NN4, is required:

var value = contrl.options[contrl.selectedIndex].value;

Second Exception: Where several controls share the same name, such as radio buttons. These are made available as collections and require additional handling. For more information, see:-

www.jibbering.com/faq/faq_notes/form_access.html

Third Exception: File Inputs where most current browsers do not allow the reading of type="file" input elements in a way that is useful.

4.14 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.

msdn.microsoft.com/workshop/author/dhtml/reference/methods/close_0.asp
docs.sun.com/source/816-6408-10/window.htm#1201822

4.15 How do I modify the current page in a browser?

Using the DOM the non-standard but widely implemented innerHTML extension, the following would be sufficient to modify the content of any element that can have content: <div id="anID">Some Content</div> with script of document.getElementById("anID").innerHTML= "Some <em>new</em> Content"; Where "anID" is the (unique on the HTML page) ID attribute value of the element to modify.

The script below adds support for document.all capable browsers. Support for NN4 is also possible, but certain issues mean that it is not listed here. Using the example above, the call would be written: DynWrite('anID',"Some <em>new</em> Content") With the below code also in the page:

DocDom = (document.getElementById?true:false);
DocAll = (document.all?true:false);
DocStr=''
if (DocAll) DocStr="return document.all[id]"
if (DocDom) DocStr="return document.getElementById(id)"
GetRef=new Function("id", DocStr)
if (DocStr=='') { DynWrite=new Function("return false") } else {
  DynWrite=new Function("id", "S", "GetRef(id).innerHTML=S; return true")
}
An alternative DynWrite function:
www.jibbering.com/faq/faq_notes/alt_dynwrite.html
msdn.microsoft.com/workshop/author/dhtml/reference/properties/innerHTML.asp
www.mozilla.org/docs/dom/domref/dom_el_ref8.html#1018427

4.16 How do I trim whitespace - LTRIM/RTRIM/TRIM?

Using Regular Expressions (JavaScript 1.2/JScript 4+) :

String.prototype.lTrim =
     function()
      {
       return this.replace(/^\s+/,'');
      }
String.prototype.lTrim =
     function()
      {
       return this.replace(/\s+$/,'');
      }
String.prototype.trim =
     function()
      {
       return this.replace(/^\s+|\s+$/g,'');
      } 

or for all versions (trims characters ASCII<32 not true "whitespace"):

function LTrim(str) { 
 for (var k=0; k<str.length && str.charAt(k)<=" " ; k++) ;
 return str.substring(k,str.length);
}
function RTrim(str) {
 for (var j=str.length-1; j>=0 && str.charAt(j)<=" " ; j--) ;
 return str.substring(0,j+1);
}
function Trim(str) {
 return LTrim(RTrim(str));
}
msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/2380d458-3366-402b-996c-9363906a7353.asp
docs.sun.com/source/816-6408-10/regexp.htm

4.17 How do I force a reload from the server/prevent caching?

To reload a page, use location.reload(). However, this depends upon the cache headers that your server sends. To change this, you need to alter the server configuration. A quick fix on the client is to change the page URI so that it contains a unique element, such as the current time. For example: location.replace(location.href+'?d='+new Date().valueOf()) If the location.href already contains a Query String, use: location.replace(location.href+'&d='+new Date().valueOf())

www.mnot.net/cache_docs/
docs.sun.com/source/816-6408-10/date.htm

4.18 How do I get a perl/asp/php variable into client-side js?

Use the server-side language to generate the javascript:

var jsvar="<%= aspvar %>";
var jsvar="<?php echo $phpvar ?>";

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

In the normal browser security model, it is impossible for a script from one domain to access the properties of pages served from another domain, or a different protocol. 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.

msdn.microsoft.com/workshop/author/om/xframe_scripting_security.asp

4.20 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 Snork will generally exceed the second parameter to setTimeout and setInterval due to implementation differences among browsers.

To call the function Snork() , approx 10 seconds after the function Moomin() , you would do this:

Moomin()
setTimeout('Snork()',10000)

Script execution is not stopped, and adding Snufkin() after the setTimeout line would immediately execute the function Snufkin() before Snork()

Achieving delays through running a loop of some sort for a pre-defined period is a bad strategy, as that will tend to put CPU use up to 100% and inhibit whatever was supposed to be happening during the delay.

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

msdn.microsoft.com/workshop/author/dhtml/reference/methods/setTimeout.asp
docs.sun.com/source/816-6408-10/window.htm#1203758
en.wikipedia.org/wiki/Event-driven_programming

4.21 Why does 1+1 equal 11? or How do I convert a string to a number?

Javascript variables are loosely typed: the conversion between a string and a number happens automatically. Since plus (+) is also used as in string concatenation, '1' + 1 is equal to '11'

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.