You are on page 1of 74

About this FAQ

Question: Why this FAQ?

Answer: The goal of this FAQ is to help you develop robust client-side scripts that can
run in Netscape Navigator as well as Microsoft Internet Explorer, under various operating
systems. This FAQ collection is different from others in the following:

• Here the answers are focused on platform-independent coding, rather than on one
particular browser or platform.
• Here most answers contain interactive code examples which you can run without
leaving the Web page you are reading.
• Here you get the solution, not just a confirmation that the problem exists. For
example, other sources would just say: Sorry, JavaScript cannot read files from
the server. This FAQ gives you the solution: Here's a Java applet that helps
JavaScript read files from the server.

Back

Question: What is JavaScript?

Answer: JavaScript is a scripting language designed for adding interactivity to HTML


pages. The language was first implemented by Netscape Communications in Netscape
Navigator 2 beta (1995). JavaScript is different from the Java language (developed at Sun
Microsystems). However, the two languages can interoperate well.

JavaScript programs, or scripts, are usually embedded directly in HTML files. The script
executes when the user's browser opens the HTML file. (There is also server-side
JavaScript, but it's beyond the scope of this FAQ collection.)

JavaScript is an interpreted language. This means that scripts execute without


preliminary compilation, i.e. without conversion of the script text into a system-
dependent machine code. The user's browser interprets the script, that is, analyzes and
immediately executes it. JavaScript is supported by the following browsers:

• Netscape Navigator (beginning with version 2.0)


• Microsoft Internet Explorer (beginning with version 3.0)
• Any other browser/product whose vendor licensed or implemented JavaScript
interpreter (for example, Opera).

Thus, most Internet users today have browsers that support JavaScript. That's why
JavaScript is one of the most popular tools for adding interactive features to Web pages.

JavaScript Features
Question: What can JavaScript programs do?

Answer: The following list presents only some groups of typical tasks in which
JavaScript proves very useful:

• Giving the user more control over the browser


• Detecting the user's browser, OS, screen size, etc.
• Performing simple computations on the client side
• Validating the user's input
• Handling dates and time
• Generating HTML pages on-the-fly without accessing the Web server.

Below you'll find simple examples illustrating each of these tasks.

1. Giving the user more control over the browser.


Example: Here you can change the background color of this page as well as the text on
the browser's status bar.

And here is a Back button implemented with JavaScript. Click it, and you'll return to the
page from which you arrived:

2. Detecting the user's browser

2. Detecting the user's browser and OS. The ability to detect the user's browser and OS
allows your script to perform platform-dependent operations, if necessary.

Example. Here users of different browsers will get different greetings: We are really
glad to see a user of Microsoft Internet Explorer under Windows!

3. Performing simple computations on the client side.


Example. This is a JavaScript calculator: type an arithmetic expression, and JavaScript
will compute its value.

4. Validating the user's input.


Example. In the calculator above, try typing some letters instead of numeric input. You'll
get a warning: Invalid input characters!

Note that JavaScript helps the browser perform input validation without wasting the
user's time by the Web server access. If the user makes a mistake in the input, the user
will get an error message immediately! On the other hand, if the input information is
validated only on the server, then the user would have to wait for the server response.
5. Handling dates and time.
Example 1. This is a JavaScript clock.

Local time:

Example 2. This script says "Nice morning, isn't it?" or "Good afternoon!" or "Good
evening!" or "Wow, you are not asleep yet!?" depending on the current time. It also tells
you today's date.

Nice morning, isn't it? Today is Tuesday, 14 August 2007.

6. Generating HTML pages on the fly.


Example. The Table of Contents on the left is dynamically expandable. To view all
subsections in a section, you can click on the white arrow corresponding to that
section. To hide subsections, click on the arrow .

Every time you click on the arrows, the browser generates and displays a new HTML
page in the left frame. Thanks to JavaScript, this operation is performed on the client
machine, and therefore you don't have to wait while the information goes back and forth
between your browser and the Web server.

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

JavaScript Limitations

Question: What can't JavaScript programs do?

Answer: JavaScript code cannot do any of the following:

• use printers or other devices on the user's system or the client-side LAN
(For a workaround, see Printing JavaScript output.)
• directly access files on the user's system or the client-side LAN ; the only
exception is the access to the browser's cookie files.
(For a workaround, see the File Access section.)
• directly access files on the Web server.
(For a workaround, see the File Access section.)
• implement multiprocessing or multithreading.

If you do need to access files or perform other "privileged" operations, you can use
JavaScript in combination with a Java applet. Signed Java applets are allowed to do
"privileged" things, and your JavaScript programs can exchange information with
applets. However, you have to bear in mind the biggest JavaScript/Java limitation: the
user can always disable Java or JavaScript or both!
Back

Browsers Supporting JavaScript

Question: Which browsers support JavaScript?

Answer: JavaScript is supported by the following browsers:

• Netscape Navigator (beginning with version 2.0)


• Microsoft Internet Explorer (beginning with version 3.0)
• Any other browser/product whose vendor licensed or implemented JavaScript
interpreter (for example, Opera).

See also JavaScript Versions.

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

JavaScript Versions

Question: What JavaScript versions are there?

Answer: JavaScript is one of the youngest programming languages. It was first


implemented by Netscape Communications in 1995. The first browser to support
JavaScript was Netscape Navigator 2.0 beta version. By 1999 the two major browsers,
Netscape Navigator and Microsoft Internet Explorer, supported the following client-side
versions of JavaScript:

Browser Year JavaScript Version


Netscape Navigator 2.0 1995 JavaScript 1.0
Microsoft Internet Explorer 3.0 1996 JavaScript 1.0 (JScript 1.0)
Netscape Navigator 3.0 1996 JavaScript 1.1
Netscape Navigator 4.0 1997 JavaScript 1.2
Microsoft Internet Explorer 4.0 1997 JavaScript 1.2 (JScript 3.0)
Netscape Navigator 4.5 1998 JavaScript 1.3
Microsoft Internet Explorer 5.0 1999 JavaScript 1.3 (JScript 5.0)

Unfortunately, Netscape and Microsoft implementations of JavaScript are different, even


for the same JavaScript version number. For example, JavaScript 1.0 in Internet Explorer
3 differs from JavaScript 1.0 in Netscape Navigator 2; similarly, JavaScript 1.2 in Internet
Explorer 4 is not the same as JavaScript 1.2 in Netscape Navigator 4.
In addition to these JavaScript versions, third parties can also create their own JavaScript
implementations, or license the JavaScript technology from either Microsoft or Netscape.
For example, the Opera browsers now support JavaScript.

What does that mean for cross-platform coding? Essentially, you have to use either of the
following techniques:

• use only a subset of the JavaScript language that is supported by all target
browsers and/or
• write different code segments for different browsers, and detect the actual browser
at run time.

Be sure to test your scripts on all target platforms.

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

JavaScript Documentation

Question: Where can I get JavaScript documentation?

Answer: Online JavaScript documentation is available at these sites:

• http://www.mozilla.org/js/language/ - Mozilla.org JavaScript Resources page


• http://msdn.microsoft.com/scripting - Microsoft's JScript, DHTML info, etc.

In addition, you can find JavaScript discussions, online tutorials, links, code examples,
and hundreds of useful scripts at the following sites (of course this list is incomplete and
serves only as a starting point):

• http://www.WebReference.com/programming/JavaScript/ - tutorials and in-depth


discussions
• http://www.JavaScripts.com - lots of scripts and code examples
• http://www.24fun.com - another good site with lots of scripts
• http://www.irt.org - FAQ collections in several categories, including JavaScript
• http://www.JavaScripter.net/faq/ - this FAQ collection.

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Printing JavaScript Output

Question: How do I print JavaScript output?


Answer: JavaScript programs cannot directly access printers. However, the user can print
out everything on the Web page, including the output of JavaScript programs, by using
the File | Print menu of the browser (or the keyboard shortcut, e.g. Ctrl+P on Windows
systems).

If your script outputs data that users would often print out, then you can

• remind them to use the File | Print menu and/or


• use the window.print() method to open the print dialog.

Also, your script might generate the printable data in a separate browser window (see
example below).

Example. This script generates the multiplication table, writes it to a new browser
window and explains to the user how to print it.

Back

Comments in JavaScript

Question: How do I insert comments in JavaScript code?

Answer: JavaScript supports three different types of comments:

1. Multiple-line C-style comments. Everything between /* and */ is a comment, for


example:
2. /* This is a comment */
3. /* C-style comments can span
4. as many lines as you like,
5. as shown in this example */
6. One-line comments of C++ style. These comments begin with // and continue up
to the next line break:
7. // This is a one-line comment
8. One-line comments with the HTML comment-opening sequence (<!--). Note that
the JavaScript interpreter ignores the closing characters of HTML comments (--
>). Consider this example:
9. <!-- This is treated as a one-line JS comment
10.<!-- It works just like a comment beginning with //
11.<!-- --> This is also a one-line JS comment
12.<!-- --> because JS ignores the closing characters
13.<!-- --> of HTML-style comments

HTML-style comments are not usually found in the middle of JavaScript code.
(The // comments are simpler and easier to read.) However, it is strongly
recommended to use HTML comments for hiding JavaScript code from old
browsers.

Back
JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Hiding JS code from old browsers

Question: How do I hide JS code from old browsers that do not support JavaScript?

Answer: To prevent old browsers from displaying your JS code, do the following:

1. Immediately after the opening <script> tag, put a one-line HTML-style


comment without the closing characters, so that the first two lines of your script
would look like this:
2. <script language="JavaScript">
3. <!--
4. At the end of your script, put the following two lines:
5. //-->
6. </script>
Thus, your HTML file will contain the following fragment:
<script language="JavaScript">
<!--
Here you put your JS code.
Old browsers will treat it
as an HTML comment.
//-->
</script>

Old browsers will treat your JS code as one long HTML comment. On the other hand,
new JavaScript-aware browsers will normally interpret JS code between the tags
<script> and </script> (the first and last lines of your JS code will be treated by the
JavaScript interpreter as one-line comments).

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Is JavaScript enabled?

Question: If the user's browser cannot execute JavaScript code, can I display a
warning for the user?

Answer: Yes, you can display a special warning for users of JavaScript-incapable
browsers. Put your warning text between the tags <NOSCRIPT> and </NOSCRIPT>. Here's
an example:

<NOSCRIPT>
<H3>This page uses JavaScript</H3>
<ul>
<li>Please use Netscape Navigator 3+ or Internet Explorer 3+
<li>Make sure that JavaScript is enabled in your browser.
</ul>
</NOSCRIPT>
JavaScript-enabled browsers will ignore everything between <NOSCRIPT> and
</NOSCRIPT>. Browsers that cannot execute JavaScript will display your message on the
page.

NOTE: The <NOSCRIPT> tag is not supported by Netscape Navigator 2. Therefore, your
message will be visible to Netscape 2 users even if JavaScript is enabled in their browser.
Keep this in mind and choose a proper wording that won't mislead Netscape 2 users. (For
example, the above message assumes that your script requires at least version 3 of the
browser.)

Back

External JS Files

Question: Can I include JavaScript code from external JS files, rather than embedding
all my scripts within HTML pages?

Answer: Yes. To do so, create a new file with the extension myscript.js. Put your
JavaScript code in this file; do not include opening and closing SCRIPT tags in the
myscript.js into your Web page, use these tags in your HTML file:

.js files containing JavaScript


functions that you reuse on many different HTML pages. Please note,
however,
that some old browsers (e.g. Navigator 2.x and Explorer 3.x) cannot
load
external JavaScript files!

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Reserved words in JavaScript

Question: What reserved words are there in JavaScript?

Answer: Reserved words of the JavaScript langauge are listed below. (Some of these
words are actually used in the Java language, and are reserved in JavaScript for
compatibility purposes or as possible extensions.) When choosing names for your
JavaScript variables, avoid these reseved words!

abstract else instanceof switch


boolean enum int synchronized
break export interface this
byte extends long throw
case false native throws
catch final new transient
char finally null true
class float package try
const for private typeof
continue function protected var
debugger goto public void
default if return volatile
delete implements short while
do import static with
double in super

In addition to the above reserved words, you'd better avoid the following identifiers as
names of JavaScript variables. These are names of client-side objects, methods, or
properties in Netscape Navigator or Internet Explorer:

alert hidden outerWidth


all history packages
anchor image pageXOffset
anchors images pageYOffset
area isNaN parent
array java parseFloat
assign JavaArray parseInt
blur JavaClass password
button JavaObject pkcs11
checkbox JavaPackage plugin
clearTimeout innerHeight prompt
clientInformation innerWidth prototype
close layer radio
closed layers reset
confirm length screenX
crypto link screenY
date location scroll
defaultStatus Math secure
document mimeTypes select
element name self
elements navigate setTimeout
embed navigator status
embeds netscape String
escape Number submit
eval Object sun
event offscreenBuffering taint
fileUpload onblur text
focus onerror textarea
form onfocus top
forms onload toString
frame onunload unescape
frames open untaint
frameRate opener valueOf
function option window
getClass outerHeight

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Navigation Enhancement

• How do I code a select menu with hyperlinks to different pages?


• Can I make a button on my page work as a hyperlink to another page?
• Can I make a button on my page work as the browser's Back button?
• Can I make a button on my page work as the browser's Forward button?
• Can my script access the query string in the current URL?
• Can I pass parameters from one page to another?
• How do I search for a particular text string on the page?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Links in a Select Menu

Question: How do I code a select menu with hyperlinks to different pages?

Answer: To create a select menu like this:


you can use the following code:

<form>
<select
onChange="if(this.selectedIndex!=0)
self.location=this.options[this.selectedIndex].value">
<option value="" selected>Select a page
<option value="startpag.htm">JavaScript FAQ
<option value="numbers.htm">Numbers
<option value="strings.htm">Strings
<option value="navigati.htm">Navigation
<option value="colors.htm">Colors
<option value="http://www.javascripter.net">JavaScripter.net
</select>
</form>
Just change the menu items and the corresponding URLs to whatever you want. You can
use absolute URLs (like http://www.javascripter.net) as well as relative URLs (like
mypage.htm).

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Button Links

Question: Can I make a button on my page work as a hyperlink to another page?

Answer: To create a button that works as a


you can use this code:
<form>
<input type=button
value="insert button text here"
onClick="self.location='Your_URL_here.htm'">
</form>
Just change the button text and the target URL to whatever you want. Try it now:
You can use absolute URLs (like http://www.javascripter.net) as well as relative
URLs (like mypage.htm).

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Back Button

Question: Can I make a button on my page work as the browser's Back button?

Answer: To create your own Back button, use this code

<form>
<input type=button value="Back"
onCLick="history.back()">
</form>
Try it now:

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Forward Button

Question: Can I make a button on my page work as the browser's Forward button?
Answer: To create your own Forward button, use this code

<form>
<input type=button value="Forward"
onCLick="history.forward()">
</form>
If your browser's Forward button is currently inactive, then the Forward button on your
page won't work either. This is the case when the current page is the last page in your
browsing history. On the other hand, if you arrived to the current page using the browser's
Back button (or a scripted Back button) then the Forward button will work. Try it now!

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Query Strings

Question: Can my script access the query string in the current URL?

Answer: A query string (or search string) is an optional part of a URL that goes after the
file name and begins with a question mark (?). For example, the following URL has a
query string ?myquery after the HTML file name:

http://www.myfirm.com/file.html?myquery
Your script can access the query string in the current URL by using the JavaScript
location.search property. Click the buttons below to try it! (To view the URL in the
address line, you might want to display this page in the top-level browser window.)
These buttons have been created using the following code:
<form>
<input type=button value="Add query ?test"
onClick="self.location=
self.location.protocol+'//'
+self.location.host
+self.location.pathname+'?test'">

<input type=button value="Show query"


onClick="alert('Query string: '+self.location.search)">

<input type=button value="Remove query"


onClick="self.location=
self.location.protocol+'//'
+self.location.host
+self.location.pathname">
</form>
NOTE: query strings may not always work as expected. For example, if you save this
page on your local disk, the above buttons won't work in Internet Explorer 4.x (but they
would still work in Netscape Navigator).

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov


Passing parameters to a page

Question: Can I pass parameters from one my page to another?

Answer: Yes, you can pass a parameter to another page in several different ways:

• by storing the parameter in a cookie


• by storing the parameter in a variable of another window or frame
• by storing the parameter in the rewritable property top.name (the browser
window name)
• by appending the parameter to the destination page's URL as a query string

Here is a simple demo illustrating all these methods for passing parameters. The value to
be passed is the string 'It_worked'. When you click on the button below, the button's
event handler script stores the parameter (1) in a cookie named parm_value, (2) in a top-
level variable top.parm_value, and (3) in the top.name property. Then the script directs
your browser to the URL parm_get.htm appended with a query string containing the
URL-encoded parameter value.

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Searching for text

Question: How do I search for a particular text string on the page?

Answer: In Netscape Navigator 4.x, to search for a string use the window.find(string)
method; see also Find Dialog. In Internet Explorer 4.x and newer, create a text range
object (TRange in the example below) and use the method TRange.findText(string).

Example: The following script gets a text string from the user and then finds and
highlights this string on the page.

This example has been created using the following code:


<form name="f1" action=""
onSubmit="if(this.t1.value!=null && this.t1.value!='')
findString(this.t1.value);return false"
>
<input type="text" name=t1 value="" size=20>
<input type="submit" name=b1 value="Find">
</form>

<script language="JavaScript">
<!--
var TRange=null
function findString (str) {
if (parseInt(navigator.appVersion)<4) return;
var strFound;
if (navigator.appName=="Netscape") {

// NAVIGATOR-SPECIFIC CODE

strFound=self.find(str);
if (!strFound) {
strFound=self.find(str,0,1)
while (self.find(str,0,1)) continue
}
}
if (navigator.appName.indexOf("Microsoft")!=-1) {

// EXPLORER-SPECIFIC CODE

if (TRange!=null) {
TRange.collapse(false)
strFound=TRange.findText(str)
if (strFound) TRange.select()
}
if (TRange==null || strFound==0) {
TRange=self.document.body.createTextRange()
strFound=TRange.findText(str)
if (strFound) TRange.select()
}
}
if (!strFound) alert ("String '"+str+"' not found!")
}
//-->
</script>

JavaScript Numbers FAQ

• What types of numbers can I use in JavaScript code?


• How do I handle mathematical constants in JavaScript?
• Is there a way to use octal and hexadecimal values in JavaScript?
• How do I convert numbers to strings?
• How do I convert strings to numbers?
• How do I convert a number to a different base?
• Is there a way to test whether a particular variable holds a number or a string?
• What arithmetic operations are supported in JavaScript?
• What mathematical functions are supported in JavaScript?
• How do I generate random numbers?
• How can I round a number to n decimal places?
• Sometimes JavaScript computations seem to yield "inaccurate" results, e.g.
0.362*100=36.199999999999996. How can I avoid this?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov


Constants

Question: What types of numbers can I use in JavaScript code?

Answer: In JavaScript code, you can use the following forms of numbers:

• conventional decimal numbers:


5 137 1.3
• decimal numbers in exponential form:
6.67e-11
-1.127e20
• octal numbers, for example:
01234 -077 0312
Positive octal numbers must begin with 0 (zero) and negative octal numbers must
begin with -0.
• hexadecimal numbers, for example:
0xFF -0xCCFF 0xabcdef
Positive hexadecimals must begin with 0x and negative hexadecimals must begin
with -0x.

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Math Constants

Question: How do I handle mathematical constants in JavaScript?

Answer: Some mathematical constants are predefined in JavaScript. You can write these
constants as follows:

Math.PI // pi = 3.14159265...
Math.E // e = 2.71828182...
Math.LOG2E // log of e base 2
Math.LOG10E // log of e base 10
Math.LN2 // log of 2 base e
Math.LN10 // log of 10 base e
Math.SQRT2 // square root of 2
Math.SQRT1_2 // square root of 1/2
Thus, there is no need to remember the exact numerical value of e or pi. Just use Math.E
or Math.PI!

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Octals and Hexadecimals


Question: Is there a way to use octal and hexadecimal numbers in JavaScript?

Answer: Yes. In JavaScript you can use octals and hexadecimals.

The following are examples of octal numbers:


01234 -077 0312
Positive octal numbers must begin with 0 (zero) and negative octal numbers must begin
with -0.

And these are examples of hexadecimal numbers:


0xFF -0xCCFF 0xabcdef
Positive hexadecimals must begin with 0x and negative hexadecimals must begin with
-0x.

When you need to convert an octal or hexadecimal string to a number, use the function
parseInt(str,base). Consider these examples:

octalStr='377';
num = parseInt(octalStr,8); // num now holds 255

hexStr='7F';
num = parseInt(hexStr,16); // num now holds 127
The second argument of parseInt specifies the base of the number whose representation
is contained in the original string. This argument can be any integer from 2 to 36.

Converting Numbers to Another Base

Question: How do I convert a number to a different base (radix)?

Answer: In JavaScript 1.1, you can use the standard method Number.toString(radix)
for converting a number to a string representing that number in a non-decimal number
system (e.g. to a string of binary, octal or hexadecimal digits). For example:

a = (32767).toString(16) // this gives "7fff"


b = (255).toString(8) // this gives "377"
c = (1295).toString(36) // this gives "zz"
d = (127).toString(2) // this gives "1111111"

However, in old browsers (supporting only JavaScript 1.0) there is no standard method
for this conversion. Here is a function that does the conversion of integers to an arbitrary
base (radix) in JavaScript 1.0:

function toRadix(N,radix) {
var HexN="", Q=Math.floor(Math.abs(N)), R;
while (true) {
R=Q%radix;
HexN = "0123456789abcdefghijklmnopqrstuvwxyz".charAt(R)+HexN;
Q=(Q-R)/radix; if (Q==0) break;
}
return ((N<0) ? "-"+HexN : HexN);
}

You can test this conversion right now:

Arithmetic Operations

Question: What arithmetic operations are supported in JavaScript?

Answer: JavaScript supports the following arithmetic operations (which you can group
in brackets to form more complex expressions):

• unary operations
• binary operations
• shifts
• mathematical functions

Unary operations have one argument (in the following examples, the argument is a):

-a // change the sign of a


~a // bitwise NOT a
++a // add 1 to a (before using a)
a++ // add 1 to a (after using a)
--a // subtract 1 from a (before using a)
a-- // subtract 1 from a (after using a)

Binary operations operations have two arguments (in the following examples, the
arguments are a and b):

a * b // multiply a by b
a / b // divide a by b
a % b // find the remainder of division of a by b
a + b // add a and b
a - b // subtract b from a
a & b // bitwise a AND b
a | b // bitwise a OR b
a ^ b // bitwise a XOR b

Shifts are the following operations:

a << b // shift a by b bits to the left


// (padding with zeros)
a >> b // shift a by b bits to the right
// (copying the sign bit)
a >>> b // shift a by b bits to the right
// (padding with zeros)

Back

Number vs. String

Question: Is there a way to test whether a particular variable holds a number or a


string?

Answer: Yes. To test whether the variable holds a number or a string, use the typeof
operator. If your variable holds a number, typeof(variable) will return "number". If it
holds a string, typeof(variable) will return "string". The following are examples of
typeof usage:

typeof(123) // result: "number"


typeof("123") // result: "string"

if (typeof k == "string") { alert('k is a string.') }


if (typeof k == "number") { alert('k is a number.') }
The typeof operator can also help you distinguish between other data types. Depending
on the particular variable's value, the result of typeof can be one of the following:
"number"
"string"
"boolean"
"function"
"object"
"undefined"

Back

Math Functions

Question: What mathematical functions are supported in JavaScript?

Answer: JavaScript supports the following mathematical functions (methods of the Math
object):

Math.abs(a) // the absolute value of a


Math.acos(a) // arc cosine of a
Math.asin(a) // arc sine of a
Math.atan(a) // arc tangent of a
Math.atan2(a,b) // arc tangent of a/b
Math.ceil(a) // integer closest to a and not less than a
Math.cos(a) // cosine of a
Math.exp(a) // exponent of a
Math.floor(a) // integer closest to and not greater than a
Math.log(a) // log of a base e
Math.max(a,b) // the maximum of a and b
Math.min(a,b) // the minimum of a and b
Math.pow(a,b) // a to the power b
Math.random() // pseudorandom number in the range 0 to 1
Math.round(a) // integer closest to a
Math.sin(a) // sine of a
Math.sqrt(a) // square root of a
Math.tan(a) // tangent of a
Note that trigonometric functions assume that the argument is in radians, not degrees!

Back

Random Numbers

Question: How do I generate random numbers in JavaScript?

Answer: To generate random floating-point numbers in the range from 0 to 1, use the
Math.random() method:

num = Math.random() // num is random, from 0 to 1


If you need random floating-point numbers in the range from A to B, use this code:
num = A + (B-A)*Math.random() // num is random, from A to B

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Accuracy

Question: Sometimes JavaScript computations seem to yield "inaccurate" results, e.g.


0.362*100=36.199999999999996. How can I avoid this?

Answer: To avoid "inaccurate" results, you might want to round the results to the
precision of the data you used. For example, in order to round the result to one
thousandth, you can use this code:

roundedX = Math.round(1000*rawX)/1000;

Back

Rounding

Question: How do I round a number to n decimal places?

Answer: You can use the following code to round a number:

Math.round(10*X)/10; // round to tenths


Math.round(100*X)/100; // round to hundredths
Math.round(1000*X)/1000; // round to thousandths
...

Back

Strings

• How do I insert quotes in strings?


• How do I extract substrings from strings?
• How do I convert strings to URL-encoding?
• How do I convert strings from URL-encoding?
• How do I convert numbers to strings?
• How do I convert strings to numbers?
• How do I convert a number to a string representing that number in a non-decimal
number system?
• Is there a way to test whether a particular variable holds a number or a string?
• See also Searching for text

Back

Quotes in Strings

Question: How do I insert quotes in strings?

Answer: Quotes in strings should be preceded by a backslash. This allows the JavaScript
interpreter to distinguish a quote within the string from the quotes that serve as string
delimiters. Here's an example:

string1='It\'s five o\'clock!';


string2="<A HREF=\"index.htm\">";
Alternatively, if your string includes single quotes only, then you can use double quotes
as string delimiters, and vice versa. Here's an example:
string1="It's five o'clock!";
string2='<A HREF="index.htm">';

Back

Converting Numbers to Strings

Question: How do I convert numbers to strings in JavaScript?

Answer: The simplest way to convert any variable to a string is to add an empty string to
that variable, for example:

a = a+'' // This converts a to string


b += '' // This converts b to string
In the above examples, the resultant string will hold the decimal representation of the
original number. For converting numbers to binary, octal, or hexadecimal strings (or to
any other base) see Converting to Another Base.

Back

Question: How do I convert strings to numbers in JavaScript?

Answer: To convert a string to a number, use the JavaScript function parseFloat (for
conversion to a floating-point number) or parseInt (for conversion to an integer).

parseFloat syntax: parseFloat('string')

How it works:
The argument of parseFloat must be a string or a string expression. The result of
parseFloat is the number whose decimal representation was contained in that string (or
the number found in the beginning of the string). If the string argument cannot be parsed
as a decimal number, the results will be different in different browsers (either 0 or NaN).

Examples (comments in each line give the conversion results):

parseFloat('1.45kg') // 1.45
parseFloat('77.3') // 77.3
parseFloat('077.3') // 77.3
parseFloat('0x77.3') // 0
parseFloat('.3') // 0.3
parseFloat('0.1e6') // 100000

Back

Question: How do I extract a substring from a string?

Answer: To extract a substring from a string, use the substring method:

string.substring(start,end)
Here
string is the string from which you want to extract a substring.
start is the number specifying the position of the character at which the substring
begins. (The character at start itself will be included in the substring.)
end is the number specifying the position of the character at which the substring ends.
(The character at end will not be included in the substring.)

Note that the first character in the string corresponds to position 0, and the last character
to position string.length-1.

Examples:
'Hello'.substring(0,2) // 'He'
'Hello'.substring(0,4) // 'Hell'

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

URL-encoding

Question: How do I convert a string to URL-encoding?

Answer: To convert a string to the URL-encoded form suitable for transmission as a


query string (or, generally speaking, as part of a URL), use the escape function. This
function works as follows: digits, Latin letters and the characters + - * / . _ @ remain
unchanged; all other characters in the original string are replaced by escape-sequences
%XX, where XX is the ASCII code of the original character. Example:

escape("It's me!") // result: It%27s%20me%21

In Unicode-aware browsers (that support JavaScript 1.3) the function escape has a more
complex behavior. If the input is a Unicode string, then Unicode characters will be
converted to the Unicode escape-sequences %uXXXX.

Back

unescape

Question: How do I convert strings from URL-encoding?

Answer: To convert a string from URL-encoded form, use the JavaScript function
unescape(string). This function works as follows: if the string contains escape-
sequences of the form %XX, where XX stands for two hexadecimal digits, each escape-
sequence is replaced by the character whose ASCII code is XX. Otherwise, the string
remains unchanged.

(In Unicode-aware browsers, in addition to escape-sequences %XX, the unescape function


also processes sequences of the form %uXXXX; see also escape.)

Example:

unescape("It%27s%20me%21")
// result: "It's me!"

Back

Dialogs
• How do I generate an alert message from JavaScript?
• How do I generate an OK/Cancel dialog box from JavaScript?
• How do I generate a user prompt from JavaScript?
• What value does prompt() return if the user clicked the Cancel button?
• How do I invoke the browser's Find dialog from JavaScript?
• How do I invoke the browser's Add Favorite dialog?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Alert

Question: How do I generate an alert message from JavaScript?

Answer: To generate an alert message, use the alert() method:

alert('Message goes here')

The button above was created using the following code:

<form name=myform>
<input type=button value="Try it now"
onClick="alert('Hello from JavaScript!')">
</form>

Back

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Confirm

Question: How do I generate an OK/Cancel dialog box from JavaScript?

Answer: To generate an OK/Cancel box, use the confirm() method:

if (confirm("Your question)) {
// do things if OK
}

The button above was created using the following code:

<form name=myform>
<input type=button value="Try it now"
onClick="if(confirm('Format the hard disk?'))
alert('You are very brave!');
else alert('A wise decision!')">
</form>

Back
Prompt

Question: How do I generate a user prompt from JavaScript?

Answer: To generate a user prompt, use the prompt() method:

prompt('Prompt text','Suggested input')

The button above was created using the following code:

<form name=myform>
<input type=button value="Try it now"
onClick="f=prompt('Enter your name','Name');
alert('Hello '+f+'!')">
</form>

Canceled prompt

Question: What value does prompt() return if the user clicked the Cancel button?

Answer: The return value of canceled prompt() depends on the browser. In some
browsers the return value is null, in others it's '' (empty string). Therefore, you might
want to use the following code when calling the prompt() method:

userInput = prompt('Prompt text','Suggested input');


if (userInput != '' && userInput != null) {
// do something with the input
}

Back

Find Dialog

Question: How do I invoke the browser's Find dialog from JavaScript?

Answer: In Netscape Navigator 4.0 or newer, you can call the window.find() method to
invoke the browser's Find dialog. Try it now:

This example was created using the following code:


<form>
<input type=button value="Find (Netscape only)"
onClick="if (navigator.appName=='Netscape'
&& parseInt(navigator.appVersion)>3) window.find();
else alert('Your browser does not support \'window.find()\'!')
">
</form>
Internet Explorer does not support window.find(). However, in both Internet Explorer
and Netscape Navigator, you can use a script that finds a string on the page. For more
information, see Searching for text.
Back

Bookmarks: Add Favorite

Question: How do I invoke the browser's Add Favorite dialog?

Answer: In Internet Explorer 4.0 and newer versions, you can invoke the browser's Add
Favorite dialog by calling the method window.external.AddFavorite:
window.external.AddFavorite('URL','bookmark text').
Netscape Navigator has no similar method (and no Add Favorite dialog at all). But your
script can just remind Netscape users to create a bookmark by clicking using the
Navigator menu or keyboard shortcut (see the example below).

Example: In Internet Explorer, this script creates a hyperlink that displays the Add
Favorite dialog. In Netscape, the script reminds the user to create a bookmark by clicking
Bookmarks | Add bookmark or press Ctrl+D.

• Click here to bookmark this site.

Here's the source code of this example:


if (navigator.appName=="Netscape") {
document.write (
'To bookmark this site, click '
+'<b>Bookmarks | Add bookmark</b> '
+'or press <b>Ctrl+D</b>.'
)
}
else if (parseInt(navigator.appVersion)>3) {
document.write (''
+'<a onMouseOver="self.status=\'Bookmark this site\'" '
+' onMouseOut="self.status=\'\'" '
+' href="javascript:window.external.AddFavorite'
+'(\'http://www.JavaScripter.net/faq/\','
+'\'JavaScripter.net FAQ\')">'
+'Click here to bookmark this site</a>.'
)
}

Back

JavaScript Windows FAQ

• How do I open a new browser window?


• How do I close a window?
• How do I resize a window?
• How do I maximize a window?
• How do I write script-generated content to another window?
• How do I test whether my other window is still open?
• How do I change another window's title, that is, the content of title bar at the top
of the window?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Question: How do I open a new browser window?

Answer: To open a new browser window, use the window.open() method. For example,
the following code opens this page in a new window.

myRef = window.open(''+self.location,'mywin',
'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');

The general syntax of the window.open() method is as follows:

winRef = window.open( URL, name [ , features [, replace ] ] )


The return value, stored in the variable winRef, is the reference to your new window. You
can use this reference later, for example, to close this window (winRef.close()), give
focus to the window (winRef.focus()) or perform other window manipulations.

The parameters URL, name, features, replace have the following meaning:

URL String specifying the location of the Web page to be displayed in the new
window. If you do not want to specify the location, pass an empty string as the
URL (this may be the case when you are going to write some script-generated
content to your new window).
name String specifying the name of the new window. This name can be used in the
same constructions as the frame name provided in the frame tag within a
frameset <FRAME NAME=name ...>. For example, you can use hyperlinks of
the form <a target=name href="page.htm">, and the hyperlink destination
page will be displayed in your new window.

If a window with this name already exists, then window.open() will display
the new content in that existing window, rather than creating a new one.
features An optional string parameter specifying the features of the new window. The
features string may contain one or more feature=value pairs separated by
commas.
replace An optional boolean parameter. If true, the new location will replace the
current page in the browser's navigation history. Note that some browsers will
simply ignore this parameter.

The following features are available in most browsers:

toolbar=0|1 Specifies whether to display the toolbar in the new window.


location=0|1 Specifies whether to display the address line in the new window.
directories=0|1Specifies whether to display the Netscape directory buttons.
status=0|1 Specifies whether to display the browser status bar.
menubar=0|1 Specifies whether to display the browser menu bar.
scrollbars=0|1 Specifies whether the new window should have scrollbars.
resizable=0|1 Specifies whether the new window is resizable.
width=pixels Specifies the width of the new window.
height=pixels Specifies the height of the new window.
top=pixels Specifies the Y coordinate of the top left corner of the new window.
(Not supported in version 3 browsers.)
left=pixels Specifies the X coordinate of the top left corner of the new window.
(Not supported in version 3 browsers.)

Back

Closing a window

Question: How do I close a window?

Answer: To close a window that you previously opened from your script, you can use the
window.close() method, for example:

winRef.close();
where winRef is the window reference, as returned by the window.open() method. The
gotcha here is that the window referenced by winRef does not necessarily exist at the
time when your script attempts to close it. (The user might well have closed it already!)
And if the window no longer exists, your script may cause errors. Possible workarounds
are the following:

• Re-open the window with the same winRef and name.


• Place the window-closing code only in the window to be closed. In this case the
window reference will be self, and the code will be self.close().
• Test whether the window is still open before attempting to close it.

If your script tries to execute window.close() for the main browser window that was
opened by the user, most browsers will first invoke a dialog to ask the user whether to let
the script close the browser window. Test this yourself: here is a script that attempts to
close your browser window.

Back

Resizing a window

Question: How do I resize a window?


Answer: In Netscape Navigator 4 or Internet Explorer 4, you can resize the browser
window by using the methods window.resizeTo(newWidth,newHeight) or
window.resizeBy(DX,DY).

Note, however, that older browsers do not support these methods. The best course of
action here is probably "do nothing in an old browser". For example, this code will resize
the window to 600x400 in newer browsers, without causing errors in old browsers:

if (parseInt(navigator.appVersion)>3)
top.resizeTo(600,400);
Note also that the parameters of resizeTo() have different meaning in different
browsers: in Internet Explorer the parameters specify the outer size of the window, while
in Netscape Navigator they refer to the inner size (which does not include the window
borders, toolbar, status bar, title bar, and the address line). To resize the window to the
same outer size in both browsers, you can use this function:
function resizeOuterTo(w,h) {
if (parseInt(navigator.appVersion)>3) {
if (navigator.appName=="Netscape") {
top.outerWidth=w;
top.outerHeight=h;
}
else top.resizeTo(w,h);
}
}

Back

Maximizing a window

Question: How do I maximize a window?

Answer: To maximize the browser window, your code should determine the available
screen size and then resize the window to the user's screen size. Note that there is no
reliable way to determine the screen size in version 3 of both major browsers (except for
calling Java from Navigator 3.x). Therefore, the following sample function
maximizeWindow() only works in versions 4 and newer. Try it now:

Here's the source code:


function maximizeWindow() {
if (parseInt(navigator.appVersion)>3) {
if (navigator.appName=="Netscape") {
if (top.screenX>0 || top.screenY>0) top.moveTo(0,0);
if (top.outerWidth < screen.availWidth)
top.outerWidth=screen.availWidth;
if (top.outerHeight < screen.availHeight)
top.outerHeight=screen.availHeight;
}
else {
top.moveTo(-4,-4);
top.resizeTo(screen.availWidth+8,screen.availHeight+8);
}
}
}
A couple of remarks:

1. In Windows, maximizing a window is equivalent to

• moving the window's top left corner to the point x=-4, y=-4 and
• resizing the window to the screen size plus 8 pixels (in both horizontal and
vertical dimensions)

This allows to effectively hide the window borders. Unfortunately, Netscape Navigator 4
requires a signed script to move the window's top left corner off screen, and therefore the
above (unsigned) script leaves the window borders visible. (Before changing the window,
the Netscape-specific branch of the script checks whether the window is already
maximized. If yes, it leaves the window as is.)

2. Note also that JavaScript code cannot change the look of the maximize button (the
second button in the top right corner).

Back

Writing to a window

Question: How do I write script-generated content to another window?

Answer: To write script-generated content to another window, use the method


winRef.document.write() or winRef.document.writeln(), where winRef is the
window reference, as returned by the window.open() method.

To make sure that your script's output actually shows up in the other window, use
winRef.document.close() after writing the content. As an example, consider the
following function that opens a new window with the title Console and writes the
specified content to the new window.

writeConsole('Hello from JavaScript!');


function writeConsole(content) {
top.consoleRef=window.open('','myconsole',
'width=350,height=250'
+',menubar=0'
+',toolbar=1'
+',status=0'
+',scrollbars=1'
+',resizable=1')
top.consoleRef.document.writeln(
'<html><head><title>Console</title></head>'
+'<body bgcolor=white onLoad="self.focus()">'
+content
+'</body></html>'
)
top.consoleRef.document.close()
}
In the above example, you might notice that after you write something to the console
several times, the console window will allow you to navigate back and forth in the
output's history. This is not always a desired feature. If you would like to output the new
content without creating a new history entry, add the following operator after opening the
window (and before the first write):
docRef = top.winRef.document.open("text/html","replace");
Here winRef is the window reference returned by the window.open() method, and
docRef is a global variable in which the script stores the reference to your new document.

Back

Is my window still open?

Question: How do I test whether my other window is still open?

Answer: Let's assume that you opened a new browser window using the window.open()
method

winRef = window.open( URL, name, features )


Later on, you can check whether this window is still open by using the window.closed
property:
if (winRef.closed) alert ("It's closed!")
else alert ("It's still open!")
The window.closed property is not supported in Netscape Navigator 2 or Internet
Explorer 3. To avoid error messages, you can place the above code within a conditional
statement as follows:
if (parseInt(navigator.appVersion>2)) {
if (winRef.closed) alert ("It's closed!")
else alert ("It's still open!")
}
(Internet Explorer 3 reports that its version is 2, so the condition involving
navigator.appVersion will be true for Navigator 3 and higher and Internet Explorer 4
and higher.)

There is no simple workaround for old browsers. You might want to emulate the
window.closed property using the onUnload event handler. However, note that the
unload event is not always equivalent to closing the window. For example, this event
may occur when the user leaves the original page and goes somewhere else (and the
window remains open).

Back

Window title
Question: How do I change another window's title, that is, the content of title bar at
the top of the window?

Answer: To change another window's title, your script can write to that window a string
beginning with the following code:

'<html><head><title>Your new title here</title></head>'


Note that rewriting the other window's content will erase everything previously displayed
in that window. Therefore, if you want the window's content to stay, then, after changing
the window title, you'll have to write the old content to that window once again. (If your
script does not know what the old content was, you'd rather not change the window title
either!)

For more information on writing script-generated content to another window, see Writing
to a Window.

Back

Frames

• Is my page framed (loaded in a frameset) or is it in the browser's top-level


window?
• Bad boys from another website load my page into their frameset. How can I break
out of the frameset?
• Can I update two (or more) frames at a time?
• See also External files within layers.

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Is my page framed?

Question: Is my page framed (loaded in a frameset) or is it in the browser's top-level


window?

Answer: To test whether your page is in a frameset, you can use this conditional
operator:

if (self.location!=top.location) // if yes, you're framed


if (self.location==top.location) // here you aren't framed
Example. Let's assume that your site uses frames to provide some navigation
functionality (like this site does). Assume that your top-level frameset is in the file
/index.htm. What if a user arrives to some of your pages without frames? (This might
happen if the user arrived e.g. from a search engine.) For such users, you may want to
display an additional hyperlink to your top-level frameset - only if your page is not in the
frameset yet.
if (self.location==top.location) {
// The page is not in the frameset index.htm !!!
document.write('<p><a href="/index.htm">Home page</a>')
}
A similar code is used on this page. If you open this page in the top-level window of your
browser, you'll see an additional hyperlink Table of Contents (at the top of the page, right
under the page title). This hyperlink will bring you back to the framed view.

Back

Breaking out of a frameset

Question: Bad boys from another website load my page into their frameset. How can
I break out of the frameset?

Answer: You can just test whether your page is framed, as explained in the previous
question. If yes, you can easily break out of frames:

if (self.location!=top.location) top.location=self.location;
However, use this trick sparingly - especially if your own site also uses frames!

Back

Updating two frames at a time

Question: Can I update two (or more) frames simultaneously?

Answer: Yes. The easiest way to update several frames simultaneously is to have a
JavaScript function that loads a new page into each of the frames to be updated. For
example, if you have two frames, left and right, then the function for updating both
frames might look like this:

function updateBothFrames() {
top.left.location="newpage1.htm";
top.right.location="newpage2.htm";
}
This function can be called when the user presses a button or clicks a hyperlink. The
following example shows the HTML code for a button and hyperlink that invoke the
function:
<a href="javascript:updateBothFrames()">Click here</a>
<input type=button value="Press me" onClick="updateBothFrames()">

Back

Forms

• How do I validate the form input before sending it to the server?


• Can I save space in my form by getting more than one input value from just one
field?
• Will my form be submitted when the user presses the Enter key?
• How do I disable a radio button (making it not selectable)?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Validating a Form

Question: How do I validate the form input before sending it to the server?

Answer: To validate the form input, call your validation function from the form's
onSubmit event handler. When the user submits the form, the browser will first invoke
the onSubmit event handler. The form will actually be submitted to the server only if the
handler returns true. In the following example, the onSubmit event handler validates the
user's email address. (For simplicity, the address is considered to be valid if it does not
contain spaces, contains the @ character and if @ is neither the first nor the last
character.) Note that the handler itself must contain a return statement in order to return
the value true or false to the browser.

Your email:
This example used the following code:
<script language="JavaScript">
<!--
function isValid() {
var email=document.form1.t1.value;
if (email.indexOf(' ')==-1
&& 0<email.indexOf('@')
&& email.indexOf('@')+1 < email.length
) return true;
else alert ('Invalid email address!')
return false;
}
//-->
</script>

<form name=form1
method=post
action="javascript:alert('The form is submitted.')"
onSubmit="return isValid()">
Your email:
<input type=text name=t1 size=20 >
<input type=submit value=Submit>
</form>

Back

Combining Input Fields

Question: Can I save space in my form by getting more than one input value from just
one text field?
Answer: Yes. For example, you can display a text input field and a select box. Using the
select box, the user will be able to choose which kind of value to input in the text field.
All input data can actually be submitted to the server in additional hidden form elements.
Try this example:

This form was created using the following JavaScript code:


<form name=form1 action="" onSubmit="return validate()">
<input name="name" type=hidden value="">
<input name="email" type=hidden value="">
<input name="country" type=hidden value="">
<select name=s1 onChange="refill()">
<option value="name" selected >Your name:
<option value="email" >Your email address:
<option value="country" >Your country:
</select>
<input name=t1 type=text value="" size=20>
<input name=b1 type=submit value="Enter!">
</form>

<script language="JavaScript">
<!--
isFilled=new Array(0,0,0);
oldActiveField="name"; oldIndex=0;
theActiveField="name"; theIndex=0;
theValue='';
theForm=document.form1;

function refill() {
oldIndex=theIndex;
theIndex=theForm.s1.selectedIndex;
oldActiveField=theActiveField;
theActiveField=theForm.s1.options[theIndex].value;
theValue=theForm.t1.value;
eval('theForm.'+oldActiveField+'.value=theValue');
eval('theForm.t1.value=theForm.'+theActiveField+'.value');
if (theValue!='') isFilled[oldIndex]=1;
if (theValue=='') isFilled[oldIndex]=0;
}

function read() {
oldIndex=theForm.s1.selectedIndex;
oldActiveField=theForm.s1.options[oldIndex].value;
theValue=theForm.t1.value;
eval('theForm.'+oldActiveField+'.value=theValue');
if (theValue!='') isFilled[theIndex]=1;
if (theValue=='') isFilled[theIndex]=0;
}

function validate() {
read();
for (var k=0; k<isFilled.length; k++) {
if (!isFilled[k]) {
theIndex=k;
theForm.s1.selectedIndex=k;
theForm.t1.value='';
theActiveField=theForm.s1.options[k].value;
if (oldIndex==k) alert ('Please fill in your '+theActiveField)
return false;
}
}
alert ('You are submitting the following data:'
+'\nName: '+theForm.name.value
+'\nEmail: '+theForm.email.value
+'\nCountry: '+theForm.country.value
)

return false;
// Instead of returning false in all cases,
// a real-life code here would validate the data
// and return true if the user submitted valid data
}

//-->
</script>

Back

Will the Enter key work?

Question: Will my form be submitted when the user presses the Enter key?

Answer: In most browsers, pressing the Enter key will submit your form if the form has
only one text input field. (The form may also have other input elements, such as
checkboxes, select boxes, radio buttons, password, hidden elements etc.)

Back

Disabling a Radio Button

Question: How do I disable a radio button in a form (making it not selectable)?

Answer: To make a radio button not selectable, in the button's INPUT tag you can use an
onClick event handler like this:

<INPUT type="radio" name="myButton" value="theValue"


onClick="this.checked=false;
alert('Sorry, this option is not available!')">
In the example below, the "Courier delivery" option is disabled. Try it now - you'll get an
alert box with the text Sorry, this option is not available!
Delivery method (choose one):
download
regular mail
courier delivery
Back

Layers

• Can I display an external HTML file as part of my page?


• How do I create a new layer from JavaScript?
• How do I delete a layer using JavaScript?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

External Files Within Layers

Question: Can I display an external HTML file as part of my page?

Answer: Yes, you can display an external HTML file on your page by using:

LAYER or ILAYER tags with SRC=FILENAME.HTM (in Netscape 4)


IFRAME tag with SRC=FILENAME.HTM (in Explorer 4+ and Netscape 6)
You can use JavaScript to detect the browser name and version (see Client Information)
and then generate the necessary IFRAME or LAYER tags.

Here's an example:

In the above example, we've created a JavaScript function insertExternalFile()


for detecting the client browser and generating the necessary tags. In order to insert an
external file, we called insertExternalFile() passing the file name as a parameter.
The function also takes two other parameters: the width and height of the area where
you'd like to display the inserted file. Thus, each of the external files inserted_file1.htm
and inserted_file2.htm was embedded in the page using the following code:

insertExternalFile("inserted_file.htm",layer_width,layer_height)

The JavaScript code of the function insertExternalFile() is contained within the


HEAD section of the page:

<script language="JavaScript">
<!--
function insertExternalFile(fname,W,H) {
if (navigator.appName.indexOf("Microsoft")!=-1
|| navigator.appName=="Netscape"
&& parseInt(navigator.appVersion)>4
)
{
document.write(''
+'<IFRAME src="'+fname+'" scrolling="no" frameborder=0 border=0'
+(W==null ? '' : ' width='+W)
+(H==null ? '' : ' height='+H)
+'></IFRAME>'
)
}

if (navigator.appName=="Netscape"
&& parseInt(navigator.appVersion)==4) {
document.write(''
+'<ILAYER>'
+'<LAYER src="'+fname+'" '
+(W==null ? '' : ' width='+W)
+(H==null ? '' : ' height='+H)
+'></LAYER></ILAYER>'
)
}
}
//-->
</script>

Copyright © 2000, Alexei Kourbatov

Creating Layers

Question: How do I create a new layer from JavaScript?

Answer: Normally, you create layers by using DIV tags in the HTML source code of
your page. However, you can also create layers programmatically with JavaScript! Here's
an example:

The above example has been created using this code:

<form>
<input type=button value="Create layer"
onClick="makeLayer('LYR1',200,10,100,100,'red',1,1)">
<input type=button value="Delete layer"
onClick="deleteLayer('LYR1')">
</form>
To create a new layer, this code calls the function makeLayer:
makeLayer(ID,left,top,width,height,color,visible,zIndex)
And here's the JavaScript source code of this function:
function makeLayer(id,L,T,W,H,bgColor,visible,zIndex) {
if (document.layers) {
if (document.layers[id]) {
alert ('Layer with this ID already exists!')
return
}
var LR=document.layers[id]=new Layer(W)
LR.name= id
LR.left= L
LR.top = T
LR.clip.height=H
LR.visibility=(null==visible || 1==visible ? 'show' : 'hide')
if(null!=zIndex) LR.zIndex=zIndex
if(null!=bgColor) LR.bgColor=bgColor
}
else if (document.all) {
if (document.all[id]) {
alert ('Layer with this ID already exists!')
return
}
var LR= '\n<DIV id='+id+' style="position:absolute'
+'; left:'+L
+'; top:'+T
+'; width:'+W
+'; height:'+H
+'; clip:rect(0,'+W+','+H+',0)'
+'; visibility:'+(null==visible || 1==visible ? 'visible':'hidden')
+(null==zIndex ? '' : '; z-index:'+zIndex)
+(null==bgColor ? '' : '; background-color:'+bgColor)
+'"></DIV>'
document.body.insertAdjacentHTML("BeforeEnd",LR)
}
}

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Deleting Layers

Question: How do I delete a layer from JavaScript?

Answer: Here's the example that you've already seen in the Creating Layers section:

This example was created using the following code:

<form>
<input type=button value="Create layer"
onClick="makeLayer('LYR1',200,10,100,100,'red',1,1)">
<input type=button value="Delete layer"
onClick="deleteLayer('LYR1')">
</form>
To delete a layer, given the layer's ID, this code calls the function deleteLayer(id).
Here's the JavaScript source code of this function:
function deleteLayer(id) {
if (document.layers && document.layers[id]) {
document.layers[id].visibility='hide'
delete document.layers[id]
}
if (document.all && document.all[id]) {
document.all[id].innerHTML=''
document.all[id].outerHTML=''
}
}

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Images
• How do I change an image when the user's mouse points at it?
• How do I change an image when the user clicks on it?
• Can I create "pressable" buttons with images?

Back

JavaScripter

OnMouseOver Effects

Question: How do I change an image when the user's mouse points at it?

Answer: Here is a simple example:


Point at this folder, and it will open. Move the mouse away, and the folder will close.

In this example, the image is 2.gif; the image is 1.gif. Both files are stored in the
../hi-icons directory. In order to create the "mouseover" effect, the <IMG> tag is
embedded in a hyperlink that has onMouseOver and onMouseOut event handlers:

<a href="#any_URL"
onMouseOver="handleOver();return true;"
onMouseOut="handleOut();return true;"
><img name=imgName width=17 height=15 border=0
alt="This image changes when you point at it!"
src="../hi-icons/2.gif"
></a>
In the <HEAD> section of the page, we have JavaScript code that preloads the image files
and defines the event handler functions:
<script language="JavaScript">
<!--
// PRELOADING IMAGES
if (document.images) {
img_on =new Image(); img_on.src ="../hi-icons/1.gif";
img_off=new Image(); img_off.src="../hi-icons/2.gif";
}

function handleOver() {
if (document.images) document.imgName.src=img_on.src;
}

function handleOut() {
if (document.images) document.imgName.src=img_off.src;
}

//-->
</script>

Here is a more complex example with several images:


The code is very similar to the above, except that now the event handler functions take
the image's number as a parameter. (To see the actual code, view the source of this page.)
Back

OnMouseDown Effects

Question: How do I change an image when the user clicks on it?

Answer: This is very similar to onMouseOver effects. However, the techniques described
on this page will work only in Netscape 4.x or Internet Explorer 4.x (or newer browsers)
because versions 3.x of both browsers do not support the onMouseDown and onMouseUp
event handlers.

Here is a simple example:


Press the mouse button while pointing at this folder, and it will open. Release the mouse
button, and the folder will close.

The <IMG> tag in this example is embedded in a hyperlink that has onMouseDown,
onMouseUp and onMouseOut event handlers:

<a href="#any_URL"
onMouseDown="handlePress();return true;"
onMouseUp="handleRelease();return true;"
onMouseOut="handleRelease();return true;"
onClick="return false;"
><img name=imgName width=17 height=15 border=0
alt="This image changes when you press the mouse button!"
src="../hi-icons/2.gif"
></a>
In the <HEAD> section of the page, we have JavaScript code that preloads the image files
and defines the event handler functions:
<script language="JavaScript">
<!--
// PRELOADING IMAGES
if (document.images) {
img_on =new Image(); img_on.src ="../hi-icons/1.gif";
img_off=new Image(); img_off.src="../hi-icons/2.gif";
}

function handlePress() {
if (document.images) document.imgName.src=img_on.src;
}

function handleRelease() {
if (document.images) document.imgName.src=img_off.src;
}

//-->
</script>

Here is a more complex example with several images:


The code is very similar to the above, except that now the event handler functions take
the image's number as a parameter. (To see the actual code, view the source of this page.)
Back

Buttons with Images

Question: Can I create "pressable" buttons with images?

Answer: Yes. For each button, you'll need two images: one for the "pressed button" and
the other for the "released button". Try the following example: point at any of the buttons
below and press the left mouse button - the button image will change to "pressed" state.
To watch the button images change back to "released" state, move the (pressed) mouse
off the image and then release the mouse button.

In this example, the "pressed button" images are btn1down.gif and btn2down.gif; the
"released button" images are btn1up.gif and btn2up.gif. In order to make the buttons
"pressable", each <IMG> tag is embedded in a hyperlink that has onMouseDown,
onMouseUp, onMouseOut and onClick event handlers:

<a href="indexpg.htm"
onMouseDown="pressButton('btn1');return true;"
onMouseUp="releaseButton('btn1');return true;"
onMouseOut="releaseButton('btn1');return true;"
onClick="return true;"
><img name=btn1 width=60 height=22 border=0
alt="Index"
src="btn1up.gif"
></a>

<a href="startpag.htm"
onMouseDown="pressButton('btn2');return true;"
onMouseUp="releaseButton('btn2');return true;"
onMouseOut="releaseButton('btn2');return true;"
onClick="return true;"
><img name=btn2 width=60 height=22 border=0
alt="Home"
src="btn2up.gif"
></a>
The <HEAD> section of the page contains JavaScript code that preloads the image files and
defines the event handler functions:
<script language="JavaScript">
<!--
// PRELOADING IMAGES
if (document.images) {
btn1_down=new Image(); btn1_down.src="btn1down.gif";
btn1_up =new Image(); btn1_up.src ="btn1up.gif";

btn2_down=new Image(); btn2_down.src="btn2down.gif";


btn2_up =new Image(); btn2_up.src ="btn2up.gif";
}
// EVENT HANDLERS
function pressButton(btName) {
if (document.images)
eval('document.'+btName+'.src='+btName+'_down.src');
}

function releaseButton(btName) {
if (document.images)
eval('document.'+btName+'.src='+btName+'_up.src');
}
//-->
</script>

Back

Mouse Events

• What event properties can I use to analyze mouse events?


• How do I check whether the user clicked the left or right mouse button?
• Can I disable the Windows context menu that normally shows up when the user
clicks the right mouse button?
• Can I disable the right-click menu for a particular image, while enabling the
normal right-click menu for all other parts of my page?
• How do I detect mouse events with Ctrl, Alt, and Shift keys?
• Can I disable the default browser response for Shift-click?
• See also OnMouseOver and OnMouseDown

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Mouse Event Properties

Question: What event properties can I use to analyze mouse events?

Answer: Netscape Navigator 4 and Internet Explorer 4 (as well as newer versions)
support quite a few event properties. Some of them are the same for both browsers (for
example, event.screenX or event.type); however, most properties are platform-
dependent. Move or click your mouse, and the text boxes below will display all mouse
event properties for your browser ( Microsoft Internet Explorer):

Properties of the most recent event: Properties of the most recent event:

Back

Left vs. Right Button


Question: How do I check whether the user clicked the left or right mouse button?

Answer: The click event occurs for the left mouse button only. Therefore, onClick
event handlers do not need to preform the left-versus-right button test.

On the other hand, the mousedown and mouseup events may occur for any mouse button.
To determine whether the user clicked the left or right button, you can use the following
event properties:

event.which in Netscape Navigator


event.button in Internet Explorer

If the value of these properties is 1, the event occurred for the left button. In the following
example, the onMouseDown event handler displays the messages Left button or Right
button, depending on the mouse button you actually have clicked. The messages will
appear on your browser's status bar. Click or right-click anywhere on this page to see it
work:

<script language="JavaScript">
<!--
function mouseDown(e) {
if (parseInt(navigator.appVersion)>3) {
var clickType=1;
if (navigator.appName=="Netscape") clickType=e.which;
else clickType=event.button;
if (clickType==1) self.status='Left button!';
if (clickType!=1) self.status='Right button!';
}
return true;
}
if (parseInt(navigator.appVersion)>3) {
document.onmousedown = mouseDown;
if (navigator.appName=="Netscape")
document.captureEvents(Event.MOUSEDOWN);
}
//-->
</script>

Back

Right Button: Disabling

Question: Can I disable the Windows context menu that normally shows up when the
user clicks the right mouse button?

Answer: In most modern browsers, you can disable the context menu by using the
oncontextmenu event handler in the body tag of your page:

<body oncontextmenu="return false;">


Try right-clicking anywhere on this page - the context menu won't show up!

In older browsers (beginning with Netscape Navigator 4.x and Internet Explorer 4.x) you
can disable the right-button menu by displaying an alert message on right-click. To do so,
insert the following code in your page's <HEAD> section:

<script language="JavaScript">
<!--
function mouseDown(e) {
if (parseInt(navigator.appVersion)>3) {
var clickType=1;
if (navigator.appName=="Netscape") clickType=e.which;
else clickType=event.button;
if (clickType!=1) {
alert ('Right mouse button is disabled.')
return false;
}
}
return true;
}
if (parseInt(navigator.appVersion)>3) {
document.onmousedown = mouseDown;
if (navigator.appName=="Netscape")
document.captureEvents(Event.MOUSEDOWN);
}
//-->
</script>
Note: In very old browsers (Netscape Navigator 3.x, Internet Explorer 3.x or earlier) the
context menu would still show up. Also, the context menu will be displayed if the user
has disabled JavaScript.

Back

Disabling the Right-Click Menu For an Image

Question: Can I disable the right-click context menu for a particular image, while still
enabling the menu for all other parts of my page?

Answer: Yes. In most modern browsers you can disable the right-click menu for a
particular image. To do so, you can use the event handler oncontextmenu="return
false;" within the IMG tag that defines your image:

<IMG border=0 src="..." oncontextmenu="return false;">


For example, the context menu has been disabled for this image:

Note: In older browsers (e.g. Internet Explorer 4.x or earlier) this trick won't work. Also,
the context menu will show up if the user has disabled JavaScript.

Back
Ctrl, Alt, Shift Keys

Question: How do I detect mouse events with Ctrl, Alt, and Shift keys?

Answer: In modern browsers, your script can check whether a mouse event occurred
while the user was pressing any of the Ctrl, Alt, Shift keys. In the example below, this is
accomplished for the MouseDown and MouseUp events. For other mouse events, a similar
strategy may or may not work, depending on the browser.

To implement the Ctrl / Alt / Shift detection, you can use the properties event.ctrlKey,
event.altKey, event.shiftKey and the deprecated Navigator-specific property
event.modifiers. Click anywhere on this page while pressing any combination of Ctrl,
Alt, and Shift keys, and the key combination will be detected by the following script (that
resides in the <HEAD> section of the page). Every time you click the mouse, you'll see the
event.ctrlKey, event.altKey, event.shiftKey or event.modifiers properties on
the browser's status bar.

<script language="JavaScript">
<!--
function mouseDown(e) {
var ctrlPressed=0;
var altPressed=0;
var shiftPressed=0;

if (parseInt(navigator.appVersion)>3) {

var evt = navigator.appName=="Netscape" ? e:event;

if (navigator.appName=="Netscape" &&
parseInt(navigator.appVersion)==4) {
// NETSCAPE 4 CODE
var mString =(e.modifiers+32).toString(2).substring(3,6);
shiftPressed=(mString.charAt(0)=="1");
ctrlPressed =(mString.charAt(1)=="1");
altPressed =(mString.charAt(2)=="1");
self.status="modifiers="+e.modifiers+" ("+mString+")"
}
else {
// NEWER BROWSERS [CROSS-PLATFORM]
shiftPressed=evt.shiftKey;
altPressed =evt.altKey;
ctrlPressed =evt.ctrlKey;
self.status=""
+ "shiftKey="+shiftPressed
+", altKey=" +altPressed
+", ctrlKey=" +ctrlPressed
}
if (shiftPressed || altPressed || ctrlPressed)
alert ("Mouse clicked with the following keys:\n"
+ (shiftPressed ? "Shift ":"")
+ (altPressed ? "Alt " :"")
+ (ctrlPressed ? "Ctrl " :"")
)
}
return true;
}
if (parseInt(navigator.appVersion)>3) {
document.onmousedown = mouseDown;
if (navigator.appName=="Netscape")
document.captureEvents(Event.MOUSEDOWN);
}
//-->
</script>
The properties event.ctrlKey, event.altKey, event.shiftKey are self-explanatory.
Their values are true if the corresponding keys are pressed, and false otherwise. The
Netscape 4 property event.modifiers is more tricky. Depending on the actual key
combination, this property has the following values:
Alt only modifiers=1 (001)
Ctrl only modifiers=2 (010)
Ctrl+Alt modifiers=3 (011)
Shift only modifiers=4 (100)
Shift+Alt modifiers=5 (101)
Shift+Ctrl modifiers=6 (110)
Shift+Alt+Ctrl modifiers=7 (111)
None of these keys modifiers=0 (000)
Thus, in the binary representation of the event.modifiers value:
the least significant (right) bit is 1 if Alt is pressed
the second bit is 1 if Ctrl is pressed
the third bit is 1 if Shift is pressed

Back

Shift-click: Disabling

Question: Can I disable the default browser response for Shift-click event?

Answer: In Netscape Navigator 4 or Internet Explorer 4 or newer browsers, you can


distinguish the Shift-click event from a simple click, and disable the default response for
Shift-click. For example, Shift-click has been disabled on this page. If you use version 4
browser (or newer) under Windows, shift-click on any hyperlink on this page to test that!
(In older browsers, you would still get the default response.)

To disable Shift-click, insert the following code in your page's <HEAD> section:

<script language="JavaScript">
<!--
function mouseDown(e) {
var shiftPressed=0;
if (parseInt(navigator.appVersion)>3) {
if (navigator.appName=="Netscape")
shiftPressed=(e.modifiers-0>3);
else shiftPressed=event.shiftKey;
if (shiftPressed) {
alert ('Shift-click is disabled.')
return false;
}
}
return true;
}
if (parseInt(navigator.appVersion)>3) {
document.onmousedown = mouseDown;
if (navigator.appName=="Netscape")
document.captureEvents(Event.MOUSEDOWN);
}
//-->
<script>

Back

Colors

• How do I change the document's background color?


• How do I change the document's text color and link colors?
• How do I convert RGB values of a color to a hexadecimal string?
• How do I convert a hex color string (e.g. "FFFFCC") to numeric RGB values of
the same color?
• What color names are supported by JavaScript?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Background Color

Question: How do I change the document's background color?

Answer: To change the background color, set the document.bgcolor property. For
example, this will change the background color to gray:

document.bgColor="#CCCCCC" // set to gray


Try it now:
This select box was created using the following code:
<form name="bgcolorForm">Try it now:
<select onChange="if(this.selectedIndex!=0)
document.bgColor=this.options[this.selectedIndex].value">
<option value="choose">set background color
<option value="FFFFCC">light yellow
<option value="CCFFFF">light blue
<option value="CCFFCC">light green
<option value="CCCCCC">gray
<option value="FFFFFF">white
</select></form>

Back
Foreground Colors

Question: How do I change the text and link colors of the document?

Answer: You might have been told that it's impossible to change the foreground colors
(that is, text and link colors) because the JavaScript properties document.fgColor,
document.linkColor and the like are read-only, and you cannot set these properties.
That means, the colors defined in the BODY tag of your page will remain unchanged no
matter what you try to set; all you can do is change the background.

Well, that's right... almost right... but try this:

It works like this: the script saves the new color settings, then reloads the page, reads the
saved settings and document.write's the BODY tag with the new colors. What? Saves?,
you might say, Can JavaScript really save files???

The trick is simple: the script can save the new color settings not in a file, but in a
variable of another window or frame. And even if there might be no other
windows/frames available, then the script still can use a cookie.

The script on this page actually uses both techniques, a cookie and a variable in the top-
level frameset. Thus, this script would fail to reset the text and link colors only if the user
disabled cookies and the page is loaded in a top-level window of the browser. If you
would like to reuse this code, just cut-and-paste it from the source of this page. Enjoy!

Just one final note: in Internet Explorer 4, the properties document.fgColor,


document.linkColor, document.vlinkColor, document.alinkColor are no longer
read-only. You can set these properties to change colors!

Back

Hex-to-RGB Conversion

Question: How do I convert a hex color string (e.g. "FFFFCC") to numeric RGB
values of the same color?

Answer: Here is a script that does this conversion:

R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");

function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}


function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
Try it yourself:
R: G: B:

Back

RGB-to-Hex Conversion

Question: How do I convert RGB values of a color to a hexadecimal string?

Answer: The algorithm is as follows: make sure that RGB values are in the range 0...255,
convert RGB values to hex strings, and then merge the three strings.

Here is a script that does this conversion:

function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}


function toHex(N) {
if (N==null) return "00";
N=parseInt(N); if (N==0 || isNaN(N)) return "00";
N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
return "0123456789ABCDEF".charAt((N-N%16)/16)
+ "0123456789ABCDEF".charAt(N%16);
}
Try it yourself:
R: G: B:

Back

Color Names

Question: What color names are supported by JavaScript?

Answer: In some old browsers (e.g. Internet Explorer 3.x) JavaScript supported only 16
color names:

aqua #00FFFF lime #00FF00 silver #C0C0C0


black #000000 maroon #800000 teal #008080
blue #0000FF navy #000080 white #FFFFFF
fuchsia #FF00FF olive #808000 yellow #FFFF00
gray #808080 purple #800080
green #008000 red #FF0000
In newer browsers, there are many more supported color names (see list below). You
can try all these colors here:

#F0F8FF aliceblue #F8F8FF ghostwhite #FFDEAD navajowhite


#FAEBD7 antiquewhite #FFD700 gold #000080 navy
#00FFFF aqua #DAA520 goldenrod #FDF5E6 oldlace
#7FFFD4 aquamarine #808080 gray #808000 olive
#F0FFFF azure #008000 green #6B8E23 olivedrab
#F5F5DC beige #ADFF2F greenyellow #FFA500 orange
#FFE4C4 bisque #F0FFF0 honeydew #FF4500 orangered
#000000 black #FF69B4 hotpink #DA70D6 orchid
#FFEBCD #EEE8AA
#CD5C5C indianred
blanchedalmond palegoldenrod
#0000FF blue #4B0082 indigo #98FB98 palegreen
#AFEEEE
#8A2BE2 blueviolet #FFFFF0 ivory
paleturquoise
#DB7093
#A52A2A brown #F0E68C khaki
palevioletred
#DEB887 burlywood #E6E6FA lavender #FFEFD5 papayawhip
#5F9EA0 cadetblue #FFF0F5 lavenderblush #FFDAB9 peachpuff
#7FFF00 chartreuse #7CFC00 lawngreen #CD853F peru
#D2691E chocolate #FFFACD lemonchiffon #FFC0CB pink
#FF7F50 coral #ADD8E6 lightblue #DDA0DD plum
#6495ED
#F08080 lightcoral #B0E0E6 powderblue
cornflowerblue
#FFF8DC cornsilk #E0FFFF lightcyan #800080 purple
#FAFAD2
#DC143C crimson #FF0000 red
lightgoldenrodyellow
#00FFFF cyan #90EE90 lightgreen #BC8F8F rosybrown
#00008B darkblue #D3D3D3 lightgrey #4169E1 royalblue
#008B8B darkcyan #FFB6C1 lightpink #8B4513 saddlebrown
#B8860B
#FFA07A lightsalmon #FA8072 salmon
darkgoldenrod
#A9A9A9 darkgray #20B2AA lightseagreen #FAA460 sandybrown
#006400 darkgreen #87CEFA lightskyblue #2E8B57 seagreen
#BDB76B darkkhaki #778899 lightslategray #FFF5EE seashell
#8B008B darkmagenta #B0C4DE lightsteelblue #A0522D sienna
#556B2F
#FFFFE0 lightyellow #C0C0C0 silver
darkolivegreen
#FF8C00 darkorange #00FF00 lime #87CEEB skyblue
#9932CC darkorchid #32CD32 limegreen #6A5ACD slateblue
#8B0000 darkred #FAF0E6 linen #708090 slategray
#E9967A darksalmon #FF00FF magenta #FFFAFA snow
#8FBC8F darkseagreen #800000 maroon #00FF7F springgreen
#483D8B
#66CDAA mediumaquamarine #4682B4 steelblue
darkslateblue
#2F4F4F
#0000CD mediumblue #D2B48C tan
darkslategray
#00CED1
#BA55D3 mediumorchid #008080 teal
darkturquoise
#9400D3 darkviolet #9370DB mediumpurple #D8BFD8 thistle
#FF1493 deeppink #3CB371 mediumseagreen #FF6347 tomato
#00BFFF deepskyblue #7B68EE mediumslateblue #40E0D0 turquoise
#696969 dimgray #00FA9A mediumspringgreen #EE82EE violet
#1E90FF dodgerblue #48D1CC mediumturquoise #F5DEB3 wheat
#B22222 firebrick #C71585 mediumvioletred #FFFFFF white
#FFFAF0 floralwhite #191970 midnightblue #F5F5F5 whitesmoke
#228B22 forestgreen #F5FFFA mintcream #FFFF00 yellow
#FF00FF fuchsia #FFE4E1 mistyrose #9ACD32 yellowgreen
#DCDCDC gainsboro #FFE4B5 moccasin

Back

File Access
• How do I read a file into a JavaScript variable?
• How do I write a file from JavaScript?
• See also Cookies for information on cookie files.

Reading a File

Question: How do I read a file into a JavaScript variable?

Answer: Reading a file from JavaScript is (almost) as easy as reading a file from a Java
applet. Your script cannot read files itself; you would have to code a Java applet that
reads files for your script.

In more detail, one of the possible reading mechanisms can work like this:

1. Your script calls a public method of the applet.


2. The public method initiates the reading process in another thread of the applet,
and then returns.
3. The reading process in another thread of the applet continues. At the same time,
the script keeps asking the applet whether the reading is complete.
4. The applet finishes reading and puts the file content in a public string variable of
the applet.
5. The script sees that the applet completed reading.
6. The script copies the file content from the applet's public variable into a Javascript
variable.

Note that unsigned Java/JavaScript code can read files only if the file(s) to read and the
code itself have the same origin. For example, if your unsigned code is published on a
Web server, it is allowed to read files from the same server only. If your code resides on
the local hard disk, it is allowed to read files only from the same disk (at best).

If you would like to read files that have a different origin, you'll need to sign your code.
(For more information, see Writing Files; very similar security considerations apply to
reading files whose origin is other than that of your code.)

Here's a simple example that implements the file reading mechanism described above.
The rectangle below is a Java applet called ReadURL.class. This applet reads the content
of the chosen file into a public variable fileContent. When finished, the applet sets its
public variable finished to 1.

The script in this example reads selected files that contain some topics from this
JavaScript FAQ.

The JavaScript code that starts the reading process looks as follows:
var fileContent='';
var theLocation='';

function readFileViaApplet(n) {
document.f1.t1.value='Reading in progress...';
document.ReadURL.readFile(theLocation);
setTimeout("showFileContent()",100);
}

function showFileContent() {
if (document.ReadURL.finished==0) {
setTimeout("showFileContent()",100);
return;
}
fileContent=document.ReadURL.fileContent;
document.form1.textarea1.value=fileContent;
}

Back

Writing a File

Question: How do I write a file from JavaScript?

Answer: Writing a file from JavaScript is just as easy as writing a file from a Java applet.
Your script cannot write files itself; it should call a Java applet's public method which
will actually do all the dirty file writing work for you.

The bad news is that

1. Writing is a privileged operation, and therefore your Java applet must be digitally
signed in order to write files.
2. Applet signing for Internet Explorer is completely different from applet signing
for Netscape Navigator.
3. Signed applets may not work properly in Netscape Navigator 3.
4. What's the worst, it's very insecure to put privileged operations in public
methods of signed applets! If you publsh such an applet, a malicious code could
easily subvert the applet's public methods, and you (the applet publisher/signer)
will be sued for any damage!

Therefore, nobody publishes scripts that write files via signed applets, although in
versions 4 of both major browsers it's technically possible.

Back

Dates and Time

• How do I write a clock program in JavaScript?


• How do I determine the week day for a given date?
• Is JavaScript code vulnerable to the Year 2000 problem?
• See also Clock bookmarklet

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Clock Example

Question: How do I write a clock program in JavaScript?

Answer: A simple clock program would retrieve a new Date() every second (or, better
yet, several times a second) and then display the time information from the Date()
object. The following code displays a clock on the browser's status bar:

function sbClock() {
var DateString=(new Date()).toString();
self.status=DateString.substring(0,3+DateString.lastIndexOf(':'));
setTimeout("sbClock()",200);
}
sbClock();

Back

Calendar Example

Question: How do I determine the week day for a given date?

Answer: To determine the week day for a given date, you set this date in a Date()
object, and then get the week day using the Date.getDay() method:

d=new Date(); d.setDate(1);

d.setYear(yyyy);
d.setMonth(mm);
d.setDate(dd);

ww=d.getDay();
if (ww==0) wDay="Sunday";
if (ww==1) wDay="Monday";
if (ww==2) wDay="Tuesday";
if (ww==3) wDay="Wednesday";
if (ww==4) wDay="Thursday";
if (ww==5) wDay="Friday";
if (ww==6) wDay="Saturday";

Back

Year 2000 Problem


Question: Is JavaScript code vulnerable to the Year 2000 problem?

Answer: You can write your code so as to make sure that it will not suffer from
"millennium bugs" even if run on older browsers. However, without special precautions,
JavaScript code can be vulnerable to the Year 2000 problem.

To avoid "millennium bugs", take into account the following:

• in most browsers, the Date.getYear() method returns the full four-digit year for
the year 2000 and all subsequent years
• in some old browsers (for example, Internet Explorer 3.0) this method returns the
year minus 1900 for all years.

The following code fragment sets the correct four-digit year in all browsers:

theDate = new Date();


theYear = theDate.getYear();
if (theYear<1900) theYear=theYear+1900;

Back

Cookies

• How do I set a cookie from JavaScript?


• How do I read a cookie with a given name?
• How do I delete a cookie with a given name?
• How do I test whether cookies are enabled in the user's browser?
• Where are cookie files actually stored on the hard disk?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Setting a Cookie

Question: How do I set a cookie from JavaScript?

Answer: To set a cookie that will expire in nDays, you can use the following function:

function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
Cookie Name:
Cookie Value:
Must expire in: days from today

Back

Reading a Cookie

Question: How do I read a cookie with a given name?

Answer: To read a cookie cookieName that has been set by the SetCookie function, you
can use the following function:

function ReadCookie(cookieName) {
var theCookie=""+document.cookie;
var ind=theCookie.indexOf(cookieName);
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(';',ind);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
Cookie Name:

Back

Deleting a Cookie

Question: How do I delete a cookie with a given name?

Answer: To delete a cookie with a given name, set a cookie that has the same name and
an expiration date in the past.

Back

Are cookies enabled?

Question: How do I test whether cookies are enabled in the user's browser?

Answer: To test whether cookies are enabled, you can set a non-empty cookie and then
retrieve it. If the retrieved cookie value is the same as you've just set, then cookies are
enabled. If the retrieved value is an empty string, then cookies are disabled.

This page contains a simple code that tests the cookies support using the functions
SetCookie and ReadCookie. Here's the result:
Cookies are currently enabled in your browser.

Back

Cookie Files Location

Question: Where are cookie files actually stored on the hard disk?

Answer: The actual location of cookie files depends on the user's browser and OS. For
example, Netscape Navigator 4.x under Windows stores all your cookies in a single file
cookies.txt; a typical location of this file is the following:

c:\Program Files\Netscape\Users\Your_Name\cookies.txt
Internet Explorer 4.x stores each cookie in a separate file. The name of a cookie file is
something like this: anyuser@WebSiteName.txt. A typical location of cookie files in
Internet Explorer 4.x is the following:
c:\Windows\Cookies\anyuser@WebSiteName.txt

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Client Information

• How do I detect the browser name (vendor)?


• How do I detect the browser version?
• How do I detect the operating system on the client machine?
• How do I get the screen size on the client machine?
• How do I get the browser window size?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Browser Name

Question: How do I detect the browser name (vendor)?

Answer: To eastablish the actual name of the user's Web browser, you can use the
navigator.appName and navigator.userAgent properties. The userAgent property is
more reliable than appName because, for example, Opera browsers (and others) may
return the string "Netscape" as the value of their appName for compatibility with
Netscape Navigator.

The code example below uses navigator.userAgent to implement browser detection. It


also uses navigator.appName and navigator.appVersion as a last resort only, if the
userAgent string has an "unexpected" format. In your browser, this code produces the
following output:
Browser name = Microsoft Internet Explorer
Full version = 6
Major version = 6
navigator.appName = Microsoft Internet Explorer
navigator.userAgent = Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR
1.1.4322; .NET CLR 2.0.50727)

And here is the source code that performed the browser detection in this example:

var nVer = navigator.appVersion;


var nAgt = navigator.userAgent;
var browserName = '';
var fullVersion = 0;
var majorVersion = 0;

// In Internet Explorer, the true version is after "MSIE" in userAgent


if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = parseFloat(nAgt.substring(verOffset+5));
majorVersion = parseInt(''+fullVersion);
}

// In Opera, the true version is after "Opera"


else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = parseFloat(nAgt.substring(verOffset+6));
majorVersion = parseInt(''+fullVersion);
}

// In most other browsers, "name/version" is at the end of userAgent


else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = parseFloat(nAgt.substring(verOffset+1));
if (!isNaN(fullVersion)) majorVersion = parseInt(''+fullVersion);
else {fullVersion = 0; majorVersion = 0;}
}

// Finally, if no name and/or no version detected from userAgent...


if (browserName.toLowerCase() == browserName.toUpperCase()
|| fullVersion==0 || majorVersion == 0 )
{
browserName = navigator.appName;
fullVersion = parseFloat(nVer);
majorVersion = parseInt(nVer);
}

document.write('Browser name = '+browserName+'<br>');


document.write('Full version = '+fullVersion+'<br>');
document.write('Major version = '+majorVersion+'<br>');
document.write('navigator.appName = '+navigator.appName+'<br>');
document.write('navigator.userAgent = '+navigator.userAgent+'<br>');
Back

Browser Version

Question: How do I detect the browser version?

Answer: Unfortunately, the value of navigator.appVersion is no good for detecting


the browser version. For example, in many JavaScript-aware browsers, the
navigator.appVersion value is meant to be the number of compatible Netscape
Navigator version rather than the version of the user's actual browser. (Even in the early
days of JavaScript, Microsoft Internet Explorer 3 used to return the string
navigator.appVersion that began with 2, which was intended to reflect the
compatibility with Netscape Navigator 2.)

Thus, to get the full version number of any of the above browsers, you need to rely
primarily on the navigator.userAgent string, like in the Browser Name code example.
Here is your browser's name and version:

Browser name = Microsoft Internet Explorer


Full version = 6
Major version = 6
navigator.appName = Microsoft Internet Explorer
navigator.userAgent = Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR
1.1.4322; .NET CLR 2.0.50727)

(Source code can be found in the Browser Name article.)

Back

Operating System

Question: How do I detect the operating system on the client machine?

Answer: To detect the operating system on the client machine, your script should analyze
the navigator.appVersion string. Below is a simple example of a script that sets the
variable OSName to reflect the actual client OS.

// This script sets OSName variable as follows:


// "Windows" for all versions of Windows
// "MacOS" for all versions of Macintosh OS
// "Linux" for all versions of Linux
// "UNIX" for all other UNIX flavors
// "Unknown OS" indicates failure to detect the OS

var OSName="Unknown OS";


if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

document.write('Your OS: '+OSName);


On your system, this script yields the following result:
Your OS: Windows

(To get more detailed OS information, your script should perform a more sophisticated
analysis of the navigator.appVersion string, but the idea would be the same.)

Back

Screen Size

Question: How do I get the screen size on the client machine?

Answer: To determine the screen size on the client machine, use the properties
screen.width and screen.height supported by version 4 of both major browsers. If
your user has Netscape Navigator 3 and enables Java, you use a Java call to get the screen
width and height (see the example below).

The following code sets the variables screenW and screenH to the actual width and
height of the screen, and outputs the width and height values. If the user has an old
browser, then screenW and screenH are set to 640 and 480, respectively.

var screenW = 640, screenH = 480;


if (parseInt(navigator.appVersion)>3) {
screenW = screen.width;
screenH = screen.height;
}
else if (navigator.appName == "Netscape"
&& parseInt(navigator.appVersion)==3
&& navigator.javaEnabled()
)
{
var jToolkit = java.awt.Toolkit.getDefaultToolkit();
var jScreenSize = jToolkit.getScreenSize();
screenW = jScreenSize.width;
screenH = jScreenSize.height;
}

document.write(
"Screen width = "+screenW+"<br>"
+"Screen height = "+screenH
)

In your browser, this code produces the following output:


Screen width = 1024
Screen height = 768

Back

Browser Window Size

Question: How do I get the browser window size?

Answer: To determine the actual size of the browser window, use the following
properties:

• in Netscape Navigator 4:
window.innerWidth, window.innerHeight
• in Microsoft Internet Explorer:
document.body.offsetWidth, document.body.offsetHeight

Note that the code that uses document.body.offsetWidth and


document.body.offsetHeight must be executed after the browser has parsed the
<BODY> tag.

The following code sets the variables winW and winH to the actual width and height of the
browser window, and outputs the width and height values. If the user has an old browser,
then winW and winH are set to 630 and 460, respectively.

var winW = 630, winH = 460;

if (parseInt(navigator.appVersion)>3) {
if (navigator.appName=="Netscape") {
winW = window.innerWidth;
winH = window.innerHeight;
}
if (navigator.appName.indexOf("Microsoft")!=-1) {
winW = document.body.offsetWidth;
winH = document.body.offsetHeight;
}
}

document.write(
"Window width = "+winW+"<br>"
+"Window height = "+winH
)

In your browser, this code produces the following output:


Window width = 806
Window height = 460
Note that if the above code executes within a frame, it will give you the frame's width
and height.

To adjust the width and height values taking into accout the scrollbars:

• in Netscape Navigator: subtract 16 from the width and height


• in Microsoft Internet Explorer: subtract 20 from the width and height

Thus, the code adjusted for scrollbars might look as follows:


if (parseInt(navigator.appVersion)>3) {
if (navigator.appName=="Netscape") {
winW = window.innerWidth-16;
winH = window.innerHeight-16;
}
if (navigator.appName.indexOf("Microsoft")!=-1) {
winW = document.body.offsetWidth-20;
winH = document.body.offsetHeight-20;
}
}

Back

Bookmarklets

• What's a bookmarklet?
• What browsers support bookmarklets?
• What's the maximum length of bookmarklet code?
• Bookmarklet example: Calculator
• Bookmarklet example: Clock
• Can I have a JavaScript interpreter bookmarklet?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

What's a Bookmarklet?

Question: What's a bookmarklet?

Answer: Bookmarklet is a tiny JavaScript program contained entirely in a hyperlink's


URL. (JavaScript URLs look like this: <a href="javascript:the code goes
here">.) Most browsers allow you to bookmark these JavaScript URLs, just as you
bookmark any other hyperlinks. The word bookmarklet was coined by Steve Kangas,
who also developed many useful bookmarklets himself. Below is a simple example: the
go-back bookmarklet.
Go-Back Bookmarklet
This bookmarklet is an equivalent of the browser's Back button. To preview the
bookmarklet, click on the above title. To add it to your bookmarks, right-click on the title
and choose Add bookmark or Add to Favorites (depending on your browser).

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Bookmarklets: Browser Support

Question: What browsers support bookmarklets?

Answer: Bookmarklets are supported by the following browsers:

Netscape Navigator 3.0 and newer versions


Internet Explorer 4.0 and newer versions

Not all bookmarklets will work in any browser. This is due to the differences in
JavaScript implementations in different browsers. To write a cross-browser bookmarklet:

Use JavaScript subset that is supported in all target browsers.


Make sure that the bookmarklet code is not too long.

Back

Bookmarklets: Maximum Length

Question: What's the maximum length of bookmarklet code?

Answer: The maximum length of bookmarklet code depends on the browser.

Experiments show that the toughest requirements are in Internet Explorer 6.x. Any
bookmarklet with code length exceeding ~510 characters might not work in IE6.

Back

Calculator Bookmarklet

Question: Can I have a calculator in my bookmarks file?

Answer: Yes, here is a bookmarklet calculator.

To preview the calculator, click on the above hyperlink. To close the calculator, click
Cancel in the calculator prompt box. To add the calculator to your bookmarks, right-click
on the hyperlink and choose Add bookmark or Add to Favorites (depending on your
browser).
This bookmarklet has been tested with both NS4 and MSIE4.

Back

JavaScripter

JavaScript Interpreter Bookmarklet

Question: Can I have a bookmarklet with the JavaScript interpreter?

Answer: Yes. In fact, some JS programmers find that a JavaScript interpreter


bookmarklet is very useful. Not only it allows to execute a line of JavaScript code on-the-
fly - it also helps you check the state of any variable in your code while viewing your
HTML page. Here it is - the JavaScript interpreter bookmarklet.

• To get the JavaScript interpreter prompt, click on the above hyperlink.


• To check the state of a JS variable, enter the variable name.
• To execute a line of JS code, enter the code.
• To close the interpreter prompt, click Cancel in the prompt box.
• To add the JavaScript interpreter to your bookmarks, right-click on the hyperlink
and choose Add bookmark or Add to Favorites (depending on your browser).

This bookmarklet has been tested with both NS4 and MSIE4.

Back

Sound

• What browsers can execute scripts that play sound?


• Can I play a sound file without using JavaScript?
• How do I write a JavaScript function that plays a sound file?
• How do I write a JavaScript function that stops playing sound?
• Can I play a sound onMouseOver?
• How do I preload a sound file?
• How do I set a background sound on a Web page?
• Which formats of sound files can I play on my Web page?

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Audio-enabled Browsers

Question: What browsers can execute scripts that play sound?

Answer: The techniques described in Playing Sound work in Microsoft Internet Explorer
4.0 and newer as well as Netscape Navigator 3.0 and newer. In order to play sound from
JavaScript in Internet Explorer, it's enough to test that the browser version is 4.0 or
newer. In Netscape Navigator, you'll have to make sure that

the browser version is 3.0 or newer


Java (not only JavaScript!) is enabled
the browser recognizes the mime-type of the audio file you want to play
the LiveAudio plugin is ready to play

For example, if you want to play the sound file mySound.mid specified in the following
EMBED tag

<EMBED NAME="mySound" SRC="mySound.mid"


LOOP=FALSE AUTOSTART=FALSE HIDDEN=TRUE MASTERSOUND>
then the necessary tests can be performed using this code:
ver=parseInt(navigator.appVersion)
if (ver>2 && navigator.appName=="Netscape"
&& navigator.mimeTypes['audio/x-midi']
&& navigator.javaEnabled()
&& document.mySound.IsReady() )
{
// put Netscape-specific code here
}
if (ver>3 && navigator.appName.indexOf("Microsoft")!=-1)
{
// put Explorer-specific code here
}

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Audio File Formats

Question: Which formats of sound files can I play on my Web page?

Answer: All audio-enabled browsers support the playback of audio files in WAV and
MIDI formats (.mid, .midi, and .wav files) . Other file formats may or may not be
supported, depending on the user's browser and system configuration. For example,
RealAudio sound files will be played back only if the user installed the RealPlayer
application.

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov

Playing Sound from JavaScript

Question: How do I write a JavaScript function that plays a sound file?

Answer: There are different ways to play sound from JavaScript. Let's consider a couple
of examlpes.
Example 1. Here's the simplest cross-browser script for playing a sound file:
self.location="AUDIO_FILE_URL"

Click here to test the code of Example 1. The browser will open a separate sound control
window. The user will then have to close this window manually. Note that the script in
Example 1 is not user-friendly: every time the user clicks to run this script, the browser
will open a new sound control window - even if there might be a couple of other audio
windows already playing the same file!

Example 2. Here's a more complex example in which you won't see a separate sound
control window. (You'll find a discussion below.)

In Microsoft Internet Explorer, there are several ways to play a sound file from
JavaScript, without opening a separate window for sound control. For example, you can
use the Explorer-specific BGSOUND tag:
<BGSOUND ID="BGSOUND_ID" LOOP=1 VOLUME="-600" SRC="jsilence.mid">
Use the following JavaScript code to play a sound file mySound.mid via the BGSOUND tag:
To start playing: document.all['BGSOUND_ID'].src='mySound.mid'
To stop playing: document.all['BGSOUND_ID'].src='jsilence.mid'
Here mySound.mid stands for the name of the sound file that you actually want to play;
jsilence.mid is a "do-nothing" sound file - it does not play any sound at all, but can be
used to stop the playback of other sound files.

In Netscape Navigator, you'll have to use the LiveAudio plugin; to do so, you'll need to
put an EMBED tag on your page. For example, if you want to play the file mySound.mid
and hide the LiveAudio window, you can use the following EMBED tag:

<EMBED NAME="mySound" SRC="mySound.mid"


LOOP=FALSE AUTOSTART=FALSE HIDDEN=TRUE MASTERSOUND>
Use the following JavaScript code to control sound in Netscape:
To start playing: document.mySound.play()
To stop playing: document.mySound.stop()

The source code of Example 2 is shown below. The code first tests whether the browser
is audio-enabled and then uses the techniques described on this page. You'll see two
JavaScript functions, playSound() and stopSound(), that actually start and stop the
playback.

<BGSOUND id="BGSOUND_ID" LOOP=1 SRC="jsilence.mid">


<EMBED NAME="Bach" SRC="Bach.mid"
LOOP=FALSE AUTOSTART=FALSE HIDDEN=TRUE MASTERSOUND>

<script language="JavaScript">
<!--
ver=parseInt(navigator.appVersion)
ie4=(ver>3 && navigator.appName!="Netscape")?1:0
ns4=(ver>3 && navigator.appName=="Netscape")?1:0
ns3=(ver==3 && navigator.appName=="Netscape")?1:0
function playSound() {
if (ie4) document.all['BGSOUND_ID'].src='Bach.mid';
if ((ns4||ns3)
&& navigator.javaEnabled()
&& navigator.mimeTypes['audio/x-midi']
&& self.document.Bach.IsReady()
)
{
self.document.Bach.play()
}
}

function stopSound() {
if (ie4) document.all['BGSOUND_ID'].src='jsilence.mid';
if ((ns4||ns3)
&& navigator.javaEnabled()
&& navigator.mimeTypes['audio/x-midi']
)
{
self.document.Bach.stop()
}
}
//-->
</script>

<form name=myform>
<input type=button value="Play Sound" onClick="playSound()">
<input type=button value="Stop Sound" onClick="stopSound()">
</form>

Back

Stopping Sound

Question: How do I write a JavaScript function that stops playing sound?

Answer: If you've opened a separate sound control window using the code
self.location="AUDIO_FILE_URL" (see Example 1), then there is no simple way to
stop the sound programmatically. The user will have to close the sound control window
manually.

To be able to stop playing sound from JavaScript, you'll need to use the techniques
described in Example 2.

Let's assume that Microsoft Internet Explorer is playing the sound file mySound.mid
specified by the BGSOUND tag
<BGSOUND ID="BGSOUND_ID" SRC="mySound.mid">
To stop playing the sound, you can use this code:
document.all['BGSOUND_ID'].src='jsilence.mid'
Here jsilence.mid is a "do-nothing" sound file - it does not play any sound at all.
Now assume that Netscape Navigator is playing the sound mySound.mid specified by the
following EMBED tag:

<EMBED NAME="mySound" SRC="mySound.mid"


LOOP=FALSE AUTOSTART=FALSE HIDDEN=TRUE MASTERSOUND>
Then you can use the following code to stop the playback:
document.mySound.stop()

Back

Playing Sound onMouseOver

Question: Can I play a sound onMouseOver?

Answer: Yes, you can call a sound playback function from the onMouseOver event
handler of a hyperlink. Try this example: place your mouse pointer over the following
hyperlink, and the browser will start the playback.

J.S.Bach's Suite in B-minor


Here's the source code for this hyperlink:

<a href=#
class=playOnHover
title="This hyperlink plays a sound onMouseOver."
onClick="return false"
onMouseOver="playSound();return true"
onMouseOut ="stopSound();return true"
>&nbsp;J.S.Bach's Suite in B-minor&nbsp;</a>
The source code of the functions playSound() and stopSound() can be found in the
Playing Sound section.

Back

Preloading Sound Files

Question: How do I preload a sound file?

Answer: In Netscape Navigator 3.0 and newer, as well as in Microsoft Internet Explorer
4.0 and newer, you can use the following EMBED tag to preload a sound file mySound.mid:

<EMBED NAME="mySound" SRC="mySound.mid"


LOOP=FALSE AUTOSTART=FALSE HIDDEN=TRUE MASTERSOUND>
Then you can play the sound using the techniques described in the Playing Sound section.

Back
Background Sound

Question: How do I set a background sound on a Web page?

Answer: In all audio-enabled browsers, you can use the EMBED tag to play a background
sound. For example, if you want to play the file bkground.mid right after the browser
loads the page, you can use the following EMBED tag:

<EMBED NAME="bkgroundID" SRC="bkground.mid"


LOOP=TRUE AUTOSTART=TRUE HIDDEN=TRUE MASTERSOUND>
To stop the background sound, call the cross-browser method
document.bkgroundID.stop() - try it now!

If your target browser is Microsoft Internet Explorer (for example, in an intranet), then
you can use the Explorer-specific BGSOUND tag:

<BGSOUND ID="bkgroundID" LOOP=0 VOLUME="-600" SRC="bkground.mid">


Here, again, bkground.mid stands for the name of the sound file that you actually want
to play.

Back

JavaScripter.net. Copyright

Playing Sound without JavaScript

Question: Can I play a sound file without using JavaScript?

Answer: Yes, you can play a sound by specifying the sound file's URL as a hyperlink
destination, for example, <A HREF="mySound.mid"> (click here to try it).

When the user clicks the hyperlink, the browser will open a separate sound control
window. The user will then have to close this window manually. What's worse, every time
the user clicks the hyperlink, the browser will open a new sound control window - even
though there might be several other audio windows already playing the same file!

Back

Error Handling

• Can I suppress JavaScript error messages?


• Can I set up my own JavaScript error handler?
• Can I change the active JavaScript error handler? (Demo)

JavaScripter.net. Copyright © 1999-2006, Alexei Kourbatov


Suppressing JS Errors

Question: Can I suppress JavaScript error messages?

Answer: Yes. To suppress all JavaScript error messages on your HTML page, you can
put the following code fragment in the HEAD section of your page:

<SCRIPT language="JavaScript">
<!--
function silentErrorHandler() {return true;}
window.onerror=silentErrorHandler;
//-->
</SCRIPT>
Or you can use a similar code (without SCRIPT tags) inan included .js file, if you have
one. For a working code example, see our error handling demo!

Back

Adding Your Own Error Handler

Question: Can I set up my own JavaScript error handler?

Answer: Yes. To define your own error handler, use this JavaScript code:

function handlerFunction(description,page,line) {
// put error-handling operators here
return true
}
window.onerror=handlerFunction
Your error handler function can optionally use the following parameters:
a textual description of the error
the address (URL) of the page on which the error occurred
the number of the line in which the error occurred

The error handler function must return false if you wish to invoke the browser's default
error handler after your own handler finishes. If you don't want to invoke the browser's
default handler, your handler function must return true. For an additional code example,
check out our error handling demo!

Back

Error Handling Demo

Question: Can I dynamically change the JavaScript error handler?

Answer: Yes. To change the JavaScript error handler, just set window.onerror to the
name of the function that will serve as your new error handler.
Here's a demo that lets you test three different error handlers:

the browser's default error handler


an error handler that displays a customized alert box
a "silent" error handler that suppresses all error messages.

1. Use the select box to set or change the error handler.


2. Click Fire an Error to test the active error handler.

Below is the source code of the error handling functions used in this demo:

function defaultHandler() {return false}


function silentHandler() {return true}
function customHandler(desc,page,line,chr) {
alert(
'JavaScript error occurred! \n'
+'The error was handled by '
+'a customized error handler.\n'
+'\nError description: \t'+desc
+'\nPage address: \t'+page
+'\nLine number: \t'+line
)
return true
}

Back

JavaScripter.net FAQ: Alphabetical Index

A
About this FAQ
Accuracy
Adding Your Own Error Handler
Alert
Are cookies enabled?
Arithmetic Operations
back to top

B
Back Button
Background Color
Background Sound
Bookmarklets
Bookmarklets: Browser Support
Bookmarklets: Maximum Length
Bookmarks: Adding
Breaking out of a frameset
Browser Name
Browser Version
Browser Window Size
Browsers Supporting JS
Browsers Supporting Sound
Button Links
Buttons with Images
back to top

C
Calculator Bookmarklet
Calendar Example
Canceled Prompt
Client Information
Clock Bookmarklet
Clock Example
Closing a window
Color Names
Colors
Combining Input Fields
Comments in JavaScript
Confirm Dialog
Constants
Converting Numbers to Strings
Converting Strings to Numbers
Converting to Another Base
Cookie Files Location
Cookies
Creating Layers
Ctrl, Alt, Shift Keys
back to top

D
Dates and Time
Deleting a Cookie
Deleting Layers
Dialogs
Disabling a radio button
Disabling the Right-click Menu for an Image
back to top

E
Enter key: will it submit my form?
Error Handling
Error Handling Demo
escape
External Files in Layers
External JS Files
back to top

F
File Access
Find Dialog
Foreground Colors
Forms
Forward Button
Frames
back to top

G
General Questions
back to top

H
Hex-to-RGB Conversion
Hiding JS code from old browsers
back to top

I
Images
Is JavaScript enabled?
Is my page framed?
Is my window still open?
back to top

J
JavaScript Documentation
JavaScript FAQ
JavaScript Features
JavaScript Interpreter Bookmarklet
JavaScript Limitations
JavaScript Versions
JavaScripter.net Home
back to top

L
Layers
Left vs. Right Button
Links in a Select Menu
back to top

M
Math Constants
Math Functions
Maximizing a window
Mouse Event Properties
Mouse Events
back to top

N
Navigation
Number vs. String
Numbers
back to top

O
Octals and Hexadecimals
OnMouseDown Effects
OnMouseOver Effects
Opening a window
Operating System
back to top

P
Passing parameters to a page
Playing Sound
Playing Sound onMouseOver
Preloading Sound
Printing JavaScript Output
Prompt Dialog
back to top

Q
Query Strings
Quotes in Strings
back to top

R
Random Numbers
Reading a Cookie
Reading a File
Reserved Words
Resizing a window
RGB-to-Hex Conversion
Right Button: Disabling
Rounding
back to top

S
Screen Size
Searching for Text
Setting a Cookie
Shift-click: Disabling
Sound
Sound File Formats
Sound without JS
Stopping Sound
Strings
Substrings
Suppressing JS Errors
back to top

U
unescape
Updating two frames at a time
back to top

V
Validating a Form
back to top
W
What is JavaScript
What's a Bookmarklet?
Window title
Windows
Writing a File
Writing to a window
back to top

Y
Year 2000 Problem

http://www.javascripter.net/faq/index.htm

You might also like