Connecting Tech Pros Worldwide Help | Site Map

comp.lang.javascript FAQ - Quick Answers- 7.9 - 2003-06-30

 
LinkBack Thread Tools Search this Thread
  #1  
Old July 20th, 2005, 02:30 PM
FAQ Poster
Guest
 
Posts: n/a
Default comp.lang.javascript FAQ - Quick Answers- 7.9 - 2003-06-30


comp.lang.javascript FAQ - Quick Answers- 7.9 - 2003-06-30

1 meta-FAQ meta-questions
2 comp.lang.javascript tips
2.1 Which newsgroup deals 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 Internationalisation 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 protect a webpage in 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.05+0.01 != 0.06?
4.8 How do I communicate between frames in a web browser?
4.9 How do I find the size of a browser window?
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 parseInt('09') give an error?
4.13 How do I get the value of a SELECT box in NN?
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 in [1..N]?
4.23 How do I change print settings with window.print()?
4.24 I have <a href="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 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 the property of an object using a string?
4.40 When should I use eval?
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 7.9 it is available on the web at
<URL: http://www.jibbering.com/faq/ > in html form.
This is the official _comp.lang.javascript_ (clj) FAQ.
Or, more accurately, the meta-FAQ as 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 to help reduce the high
levels of noise on clj and to provide a resource for people new
to javascript or who want to know locations of valuable
javascript resources.

The FAQ will currently be posted in two parts, one part (the Quick
Answers) on Mondays and Fridays, with the remainder posted on
wednesdays


2 comp.lang.javascript tips

see <URL: http://jibbering.com/faq/#FAQ2 >
Or Wednesdays FAQ posting.

3 javascript resources

see <URL: http://jibbering.com/faq/#FAQ3 >
Or Wednesdays FAQ posting.

4 Quick Answers
4.1 How do I protect my javascript code?

In the main you don't, as the language is distributed in source
form, you need to deliver the source code, with JScript, there
is the Script Encoder (see MSDN) but this is nothing more than
obfuscation in effect, disabling the Right Mouse button, also
achieves nothing to protect your script in a web browser.


Your code is likely protected under copyright laws. See:
<URL: http://www.wipo.org/about-ip/en/copyright.html >
<URL: http://html.about.com/compute/html/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. You can
however use location.replace(url) in some browsers to replace the
current page in the history.

<URL: http://msdn.microsoft.com/workshop/a...ds/replace.asp >
<URL: http://devedge.netscape.com/library/...n.html#1194240 >

4.3 How can I access the client-side filesystem?

Security means that by default you can't. In a more restricted
enviroment, there are options (e.g. live connect to Java in NN,
and using FileSystemObject in IE) check
<URL: http://groups.google.com/ > for previous posts on the
subject.

<URL: http://msdn.microsoft.com/library/en...FileSystem.asp >
<URL: http://www.javaworld.com/javaworld/j...pptowin32.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.

<URL: http://tech.irt.org/articles/js064/index.htm >

4.5 How can I protect a webpage in javascript?

In practice you can't, Whilst 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
serverside. 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.

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.

Much code for trailing zeros fails for some numbers (e.g. 0.07).
The following works successfully :


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= new Function('n','return StrS(this,1,n)')

<URL: http://www.merlyn.demon.co.uk/js-round.htm >
<URL: http://msdn.microsoft.com/library/en...mthToFixed.asp >

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

Javascript numbers are represented in binary as IEEE-754
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.

<URL: http://msdn.microsoft.com/library/en...ondatatype.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 as the
frame you are in. So to access a variable called Moomin in a
frame called Snork that is in the same frameset you're in 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 a browser window?

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 (with a Formal DOCTYPE):


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

Combined:


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

<URL: http://msdn.microsoft.com/workshop/a...lientWidth.asp >
<URL: http://devedge.netscape.com/library/...ow.htm#1202446 >
<URL: http://msdn.microsoft.com/workshop/a.../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();
}
}

<URL: http://msdn.microsoft.com/workshop/a...ies/closed.asp >
<URL: http://devedge.netscape.com/library/...w.html#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();
<URL: http://msdn.microsoft.com/library/en...dhtmlprint.asp >

4.12 Why does parseInt('09') give an error?

parseInt decides what base the number is by looking at the
number. By convention it assumes any number beginning with 0 is
Octal, and any number beginning with 0x Hexadecimal. To force
use of base 10 add a second parameter parseInt("09",10)
<URL: http://msdn.microsoft.com/library/en...thparseint.asp >
<URL: http://devedge.netscape.com/library/...v.html#1064173 >

4.13 How do I get the value of a SELECT box in NN?
el=document.forms['formname'].elements['elementname'];
value=el.options[el.selectedIndex].value;

<URL: http://devedge.netscape.com/library/...t.html#1193137 >

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

The scriptwindowref.close(); windowref is window,
or self, top, parent, or a reference obtained when opening the
window, you can only close windows opened by script, no others.

<URL: http://msdn.microsoft.com/workshop/a...ds/close_0.asp >
<URL: http://devedge.netscape.com/library/...ow.htm#1201822 >

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

At its simplest in current DOM2 (with innerHTML extension) (IE5+
NS6 ) then having HTML of <div id="aID">Some
Content</div> with script of
document.getElementById("aID").innerHTML="Some
<em>new</em> Content"; works.

The below adds document.all capable browsers to the mix, NS4
could also be done but had serious issues, so is not listed
here. HTML:<div
ID=aID></div> and
script DynWrite('aID',"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")
}

<URL: http://msdn.microsoft.com/workshop/a.../innerHTML.asp >
<URL: http://www.mozilla.org/docs/dom/domr...8.html#1018427 >

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

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


String.prototype.LTrim=new Function("return this.replace(/^\\s+/,'')")
String.prototype.RTrim=new Function("return this.replace(/\\s+$/,'')")
String.prototype.Trim=
new 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));
}

<URL: http://msdn.microsoft.com/library/en...xpressions.asp >
<URL: http://devedge.netscape.com/library/...nce/regexp.htm >

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

To reload a page, location.reload() works, however this does
depend on the cache headers that your server sends, to change
this you need to change your server - a quick fix to this on the
client side is to change the URI of the page so it contains a
unique element such as the current
date. location.replace(location.href+'?d='+new
Date().valueOf()) of if the location.href already
contains a Query String
location.replace(location.href+'&d='+new
Date().valueOf())
<URL: http://www.mnot.net/cache_docs/ >
<URL: http://devedge.netscape.com/library/...rence/date.htm >

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

You have the serverside language generate the javascript:


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

etc. For communication between client and server, after a page
has loaded, there are a number of "Remote Scripting"
options available:

<URL: http://www.ashleyit.com/rs/main.htm >

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

In the normal browser security it is impossible for a script
from one domain to access properties of pages served from
another domain or by a different protocol, and any attempt by
your script to access a property of a window in a different
domain will result in a permission denied error. Signed scripts,
or trusted ActiveX's can overcome this in limited situations.

<URL: http://msdn.microsoft.com/workshop/a...g_security.asp >

4.20 How do I make a 10 second delay?

There is no ability to cause a delay in javascript, host Object
Models usually provide something. In the browser, there is
window.setTimeout which can be used to create a delay.

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()
Other hosts have different wait functions such as Windows Script
Hosts WScript.Sleep()
<URL: http://msdn.microsoft.com/workshop/a...setTimeout.asp >
<URL: http://devedge.netscape.com/library/...ow.htm#1203758 >

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

Javascript variables are loosely typed, and conversion between
Strings and Numbers happen freely, since + is also used for
String concatenation, "1"+1 is equal to
11 - the String deciding what + does, to overcome
this convert the String to a number: Number("1")
or "1"*1 or "1"-0 or
parseInt("1",10) or parseFloat("1")
or +varname. Prompt and Form element values are
all Strings, so convert them to numbers before performing
addition.

<URL: http://msdn.microsoft.com/library/en...condeclare.asp >

4.22 How do I generate a random integer in [1..N]?
function Random(x) { return Math.floor(x*Math.random()) }

gives a random number between 0..(x-1);
Random(N)+1 for [1..N]

<URL: http://msdn.microsoft.com/library/en...smthrandom.asp >
<URL: http://devedge.netscape.com/library/...th.htm#1197697 >

Dealing and Shuffling:
<URL: http://www.merlyn.demon.co.uk/js-randm.htm >

4.23 How do I change print settings with window.print()?

In a normal security enviroment, you can't change anything. The
page stylesheet rules provide some options, but are not supported
in browsers yet. If you can, use an ActiveX or Plugin ScriptX and
Neptune from Meadroid to give you more control for Windows
versions of Internet Explorer and Netscape 4,6 and Opera 5.

<URL: http://www.meadroid.com/scriptx/ >
<URL: http://msdn.microsoft.com/library/en...dhtmlprint.asp >

4.24 I have <a href="javascript:somefunction()"> what ... ?

Whatever the rest of your question, this is generally a very bad
use of the javascript pseudo protocol. It was designed to be a
method that a javascript function could return the new page e.g.
javascript:"<p>Hello</p>" To use
it simply to call a function, which you then return false from,
causes user agents which do not understand javascript, or have
it disabled, to get nothing other than an error. <a
href="something.html" onclick="somefunction();return
false"> where something.html is meaningful to the
non-javascript capable, is nearly always preferable. Or use
onclick on another element so users without javascript aren't
even led to believe it does anything.

<URL: http://www.useit.com/alertbox/20021223.html >

4.25 My element is named myselect[] , how do I access it?

Form elements with any "illegal" characters can be accessed with
formref.elements["myselect[]"] - These characters
are illegal in the standard (x)HTML doctypes, so you should try
to avoid them as browsers may perform incorrectly though.

<URL: http://msdn.microsoft.com/workshop/a...s/elements.asp >
<URL: http://devedge.netscape.com/library/...rm.htm#1193375 >
<URL: http://jscript.dk/faq/php.asp >

4.26 How do I detect Opera/Netscape/IE?

The navigator object contains strings which
specify the browser and version; however, this is in general not
very genuine. Mozilla (and therefore Netscape 6) allows this to
be freely set, and Opera and IE allow it to be modified. There
are also at least 25 other javascript capable browsers with
their own strings here.

Generally though, you don't need to identify which browser is
being used. There are alternative techniques which depend on why
you want to redirect browsers - if it's to offer different CSS
stylesheets, then
<URL: http://w3development.de/css/hide_css_from_browsers/ >
shows many techniques. For Scripting, _Object_ or
_Feature_ detection is a better method to use.
<URL: http://www.xs4all.nl/~ppk/js/support.html >
Object Detection means checking that the object you wish to use
is supported by the browser before using it. This means that you
don't need to know what browsers support what methods, and your
code will automatically be usable on any browser that can
execute it.


if (document.getElementById &&
document.getElementById('el') &&
document.getElementById('el').style ) {
// We know that this browser supports getElementByID and has
// a style object, so we can set a style property.
document.getElementById('el').style.color="red";
}

Browser bugs can often be detected and overcome in similar ways.

<URL: http://developer.apple.com/internet/...detection.html >

4.27 How do I disable the right mouse button?

The event oncontextmenu of HTML attributes in IE and Mozilla, is the only
reliable and safe method of blocking the context menu, the other
approaches often presented, rarely work, and rely on alert boxes
coming up and even then are limited in their scope:
<body oncontextmenu="return false">

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

The buttons on a confirm box cannot be changed. But, why not just
change the question around such that the default answer is
OK. e.g. change "We will now buy ourselves a porsche with your
credit card, Do you want to continue with this transaction _OK_
Cancel" to "We will now buy ourselves a porsche with your credit
card, Would you like to abandon this transaction? _OK_ Cancel"


4.29 How do I log-out a user when they leave my site?

This cannot be done reliably. Here 's why:


A user may disable javascript, or may not have a javascript
capability, so the log-out script will never execute.

A user may not be connected to the Internet/Intranet when they
close your web page.

Javascript errors elsewhere in the page may prevent the script
executing.


The URL below has more information.

<URL: http://groups.google.com/groups?selm...r.ntlworld.com >

4.30 How do I format Last Modified date with javascript

The format of the document.lastModified string is
browser-dependent and sometimes misleading to users. Apparently,
new Date() appears to read it correctly, apart
from possible century error. In particular, time zone, field
order and separators may vary. It is also reliant on the server's
clock having been correctly set at the time of upload. See the
URL below.

<URL: http://www.merlyn.demon.co.uk/js-date3.htm#lM >

4.31 Why are my Rollovers so slow?

Images are cached by the browser depending on the headers sent by
the server, if the server does not send sufficient information for
the browser to decide the image is cacheable, it will check if
the image has been updated everytime you change the src of an
image (in some user settings). To overcome this you must send
suitable headers.

<URL: http://www.mnot.net/cache_docs/ >

4.32 How do I change the text in the url/location bar?

This text cannot be changed without changing the url of the page,
the normal solution is to use frames, although this does introduce
other problems.


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

In IE and some browsers you can use the Content-Disposition
header added on the server it has the format
Content-Disposition: attachment;
filename=filename.ext. This can not be done with
client-side javascript.

<URL: http://aspfaq.com/show.asp?id=2161 >
<URL: http://support.microsoft.com/support.../Q260/5/19.ASP >

4.34 How do I run a server side script?

You trigger a server-side script by setting any object's URL. For
example a frame, window, or an Image. An image will also "swallow"
the data sent back by the server so that they will not be visible
anywhere. var dummyImage = new Image();dummyImage.src = "scriptURL.asp?param=" + varName;
In win32 IE5 and Mozilla, there is the XMLHTTPRequest object, which
allows passing back of information from the server easy.

<URL: http://jibbering.com/2002/4/httprequest.html >

4.35 I have window.status="Moomin"; why doesn't the statusbar change?

When changing the status in an event (e.g. onmouseover) you
should return true from the event. Also a number of browsers
require a short delay before setting the status to overcome their
default behaviour with the statusbar.
onevent="setTimeout('window.status=\'Moomin\'',15) ;"

4.36 How do I modify the current browser window?

In a default security enviroment 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
<URL: http://msdn.microsoft.com/workshop/a...ods/open_0.asp >

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

You use the target attribute on the form, opening a window with
that name and your featuresting in the onsubmit handler of the
FORM.


<form ... target="wndname" onsubmit="window.open('',this.target,'features');r eturn true;">


<URL: http://www.htmlhelp.com/reference/ht...orms/form.html >

4.38 How do I download a page to a variable?

Within a webpage, you need to either use java, or the xml http request object, see:

<URL: http://www.galasoft-LB.ch/myjava/Web...Demo/Demo.html >
<URL: http://jibbering.com/2002/4/httprequest.html >

4.39 How do I access the property of an object using a string?

There are two equivalent ways to access properties: the dot
notation and the square bracket notation. What you are looking
for is the square bracket notation, in which the dot and the
identifier to the right of the dot are replaced with a set of
square brackets containing a string that represents the
identifier that was to the right of the dot.

//dot notation
var bodyElement = document.body;

//square bracket notation, using an expression
var bodyElement = document["bo"+"dy"];


<URL: http://www.litotes.demon.co.uk/js_info/sq_brackets.html >

4.40 When should I use eval?

The eval() function should _only_ be used when it is necessary to
evaluate a string supplied or composed at run-time; the string
can be anything from a simple (but unpredictable) expression
such as 12*2.54 to a substantial piece of javascript code.

The eval() function should not be used as a crutch in composing
member expressions; see section 4.39.


5 Comments and Suggestions
5.1 Why do some posts have <FAQENTRY> in them ?

If a poster feels that the question they are answering should be
covered in the FAQ, placing <FAQENTRY> in your post lets the FAQ
robot collect the messages for easy review and inclusion.


5.2 How do I make a suggestion?

To Make a suggestion to the FAQ, either use the FAQENTRY method
above, or email jim@jibbering.com directly, all comments,
suggestions, and especially corrections are welcome.


 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,662 network members.