Professional Documents
Culture Documents
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
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.)
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:
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 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!
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.
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
JavaScript Limitations
• 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
Back
JavaScript Versions
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.
Back
JavaScript Documentation
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):
Back
If your script outputs data that users would often print out, then you can
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
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
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:
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
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:
Back
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!
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:
Back
Navigation Enhancement
<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
Button Links
Back
Back Button
Question: Can I make a button on my page work as the browser's Back button?
<form>
<input type=button value="Back"
onCLick="history.back()">
</form>
Try it now:
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!
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'">
Back
Answer: Yes, you can pass a parameter to another page in several different ways:
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
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.
<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>
Answer: In JavaScript code, you can use the following forms of numbers:
Back
Math Constants
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
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.
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:
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);
}
Arithmetic Operations
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):
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
Back
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:
Back
Math Functions
Answer: JavaScript supports the following mathematical functions (methods of the Math
object):
Back
Random Numbers
Answer: To generate random floating-point numbers in the range from 0 to 1, use the
Math.random() method:
Back
Accuracy
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
Back
Strings
Back
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:
Back
Answer: The simplest way to convert any variable to a string is to add an empty string to
that variable, for example:
Back
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).
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).
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
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
URL-encoding
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
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.
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?
Alert
<form name=myform>
<input type=button value="Try it now"
onClick="alert('Hello from JavaScript!')">
</form>
Back
Confirm
if (confirm("Your question)) {
// do things if OK
}
<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
<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:
Back
Find Dialog
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:
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.
Back
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 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.
Back
Closing 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:
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
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
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:
• 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
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.
Back
Answer: Let's assume that you opened a new browser window using the window.open()
method
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:
For more information on writing script-generated content to another window, see Writing
to a Window.
Back
Frames
Is my page framed?
Answer: To test whether your page is in a frameset, you can use this conditional
operator:
Back
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
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
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
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:
<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
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
Answer: To make a radio button not selectable, in the button's INPUT tag you can use an
onClick event handler like this:
Layers
Answer: Yes, you can display an external HTML file on your page by using:
Here's an example:
insertExternalFile("inserted_file.htm",layer_width,layer_height)
<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>
Creating Layers
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:
<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)
}
}
Deleting Layers
Answer: Here's the example that you've already seen in the Creating Layers section:
<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=''
}
}
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?
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>
OnMouseDown Effects
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.
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>
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";
function releaseButton(btName) {
if (document.images)
eval('document.'+btName+'.src='+btName+'_up.src');
}
//-->
</script>
Back
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
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:
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
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:
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
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:
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) {
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?
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
Background Color
Answer: To change the background color, set the document.bgcolor property. For
example, this will change the background color to gray:
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.
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!
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?
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");
Back
RGB-to-Hex Conversion
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.
Back
Color Names
Answer: In some old browsers (e.g. Internet Explorer 3.x) JavaScript supported only 16
color names:
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
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:
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
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.
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
Clock Example
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
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.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
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.
• 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:
Back
Cookies
Setting a Cookie
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
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
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
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
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
Client Information
Browser Name
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.
And here is the source code that performed the browser detection in this example:
Browser Version
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:
Back
Operating System
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.
(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
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.
document.write(
"Screen width = "+screenW+"<br>"
+"Screen height = "+screenH
)
Back
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
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.
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
)
To adjust the width and height values taking into accout the scrollbars:
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?
What's a Bookmarklet?
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:
Back
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
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
This bookmarklet has been tested with both NS4 and MSIE4.
Back
Sound
Audio-enabled Browsers
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
For example, if you want to play the sound file mySound.mid specified in the following
EMBED tag
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.
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:
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.
<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
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:
Back
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.
<a href=#
class=playOnHover
title="This hyperlink plays a sound onMouseOver."
onClick="return false"
onMouseOver="playSound();return true"
onMouseOut ="stopSound();return true"
> J.S.Bach's Suite in B-minor </a>
The source code of the functions playSound() and stopSound() can be found in the
Playing Sound section.
Back
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:
Back
Background Sound
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:
If your target browser is Microsoft Internet Explorer (for example, in an intranet), then
you can use the Explorer-specific BGSOUND tag:
Back
JavaScripter.net. Copyright
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
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
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
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:
Below is the source code of the error handling functions used in this demo:
Back
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