Monday, October 20, 2008

Javascript Faqs

Q. What is JavaScript?
A. JavaScript is a scripting language designed for adding interactivity to HTML pages. 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.

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.

Q: How do I insert comments in JavaScript code?
A: JavaScript supports three different types of comments:

1. Multiple-line C-style comments. Everything between /* and */ is a comment,
for example:
/* This is a comment */
/* C-style comments can span
as many lines as you like,
as shown in this example */

2. One-line comments of C++ style. These comments begin with // and continue up to the next line break:
// This is a one-line comment

3. One-line comments with the HTML comment-opening sequence (). Consider this example:
This is also a one-line JS comment
because JS ignores the closing characters
of HTML-style comments

Q: How do I hide JS code from old browsers that do not support JavaScript?
A: To prevent old browsers from displaying your JS code, do the following:

1) Immediately after the opening

Thus, your HTML file will contain the following fragment:

Q: If the user's browser cannot execute JavaScript code, can I display a warning for the user?
A: Yes, you can display a special warning for users of JavaScript-incapable browsers. Put your warning text between the tags .
Here's an example:

This page uses JavaScript

  • Please use Netscape Navigator 3+ or Internet Explorer 3+
  • Make sure that JavaScript is enabled in your browser.

JavaScript-enabled browsers will ignore everything between . Browsers that cannot execute JavaScript will display your message on the page.

Q: 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 .js, for example, myscript.js. Put your JavaScript code in this file; do not include opening and closing SCRIPT tags in the .js file!

To embed myscript.js into your Web page, use these tags in your HTML file:

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

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

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.

Q: 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 (the browser window name)
by appending the parameter to the destination page's URL as a query string

Q: 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')

Q: 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.') }

Q: 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

Q: How do I extract a substring from a string?
Answer: To extract a substring from a string, use the substring method:


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.


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

Q: Can I play a sound file without using JavaScript?
A: Yes, you can play a sound by specifying the sound file's URL as a hyperlink destination, for example,

Q: How do I set a background sound on a Web page?
A: 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:

To stop the background sound,call the cross-browser method document.bkgroundID.stop() .

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

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

Q: How do I generate a user prompt from JavaScript?
A: To generate a user prompt, use the prompt() method:

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

use the following code:

Q: What value does prompt() return if the user clicked the Cancel button?
A: 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

Q: How do I disable a radio button in a form (making it not selectable)?
A: To make a radio button not selectable, in the button's INPUT tag you can use an onClick event handler like this:

Q: How do I change an image when the user's mouse points at it?
A: 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 tag is embedded in a hyperlink that has onMouseOver and onMouseOut event handlers:

This image changes when you point at it!

In the section of the page, we have JavaScript code that preloads the image files and defines the event handler functions:

Q: How do I check whether the user clicked the left or right mouse button?
A: 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:

Q: Can I disable the Windows context menu that normally shows up when the user clicks the right mouse button?
A: In most modern browsers, you can disable the context menu by using the oncontextmenu event handler in the body tag of your page:

Q: 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:

Q: How do I determine the week day for a given date?
A: 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();


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

Q: How can I show a different image each day?
we can display a different image for each day of the week:

This creates a date object and then gets the number of the day of the week, and then uses that to display the relevant image.

If you have more than 7 images then you'll need to alter this, either using the day of the month or the day of the year, or maybe even the day of the millennium!

Q: How do I display a random banner image?
A:There is an existing JavaScript method that returns a random number:

//Returns a random number between 0 and 1
function getRandom() {
return Math.random()

In Netscape Navigator 2 this only works on Unix platforms, so you might want to try the following instead:

To create a random number between 1 and 10 use rand(10). To display an random image named banner1.gif to banner10.gif use:

Q: How do I disable the "Back" button of a browser?

Easy answer - you can't.

Longer answer - you cannot totally remove the ability for the user to go back to the previous location, although you can make it harder.

1) You can use the location replace method when changing the location. This replaces the current history location with the new location. However older browsers do not support this method, which is why it is required to test for the images object:

Note: in Opera replace() will work, but only with absolute URL's.

2) You can load the new location into another window, and then close the old window:

In the first page:

Open Window

In the next window:

change location

3) You can open a window without a toolbar:

However, this does not totally stop the user from being able to go back to the previous page.

4) You can add code to the previous page to force the browser to go forwards again:

Q: What's the difference between Java and JavaScript and why should I prevent my browser from executing JavaScript?
JavaScript is an OO type interpreted language that runs on the clients browser, enabling interaction between the user and the document, without the need to always go back to the server for processing. for example to validate form input. There is no reason why you would want to stop JavaScript from executing on your browser, unless yet another security hole is found in the browser that allows data to be captured by a third party. All the *known* security holes have been plugged.

Java is a byte compiled language that is a fully fledged OO language. It again runs on the clients browser. It can do things that JavaScript cannot do, like reading a file on the same server that the document was served from (I believe this is correct). It can do graphcs. I'm not too sure if there are valid reasons why you would not want to allow Java to execute on your browser, other than that Java applets can be quite big and can take a while to download. The initial loading of Java in the browser can take quite a few seconds to start up.

Q: Is there a way to close a window without that confirm message?
The only way to avoid the message appearing is when you close a window that only has one location in its history. Most visitors to a site will have many locations in their current history.

If you are creating a window that you then want to close later on without the message occurring, then make sure that you use the JavaScript replace() method when changing the location within that window, that way you will not create new entries within that windows history object.

To use the replace method without causing errors on browsers that don't support it you'll need to do the following:

And then for all your links in that window:

Next Page

Make sure you use the absolute URL, because in some versions of Opera, an absolute reference will cause problems when used with the replace() method.

Note that for browsers that don't support the replace method (the same as those that don't support the image object) the window will build up entries in the history object.

Q: How can I disable the "View Source" menu item?
Sorry, not possible.

Q: How can I calculate the number of days elapsed between two dates?

Q: How do you subtract X hours from a date?

The following subtracts five hours from the current date and time:

Q: How can I calculate the difference between two dates?

Q: How can I calculate the number of days in the current month?
The following little gem was provided by Paul Bennett. At first look it looks too simple, but on closer investigation it is a pretty clever piece of code:

function days_in_month (year, month) {
return 32 - new Date(year, month, 32).getDate();

Q: How can I convert a text string: "Wed Aug 26 14:40:45 MET DST 1998." into a Date object?
The date foramt has to be altered to:

Wed, 26 Aug 1998 14:40:45So:

Q: How can I convert a mm/dd/yy date to dd/mm/yy and vice versa?

Q: How do I add a number of days to a date?

Q: How can I cancel the users F5 request to refresh the page in Internet Explorer?

Do it by redirecting the keyboard action on another keycode that you can control (backspace in this example):

function cancelRefresh() {
// keycode for F5 function
if (window.event && window.event.keyCode == 116) {
window.event.keyCode = 8;
// keycode for backspace
if (window.event && window.event.keyCode == 8) {
// try to cancel the backspace
window.event.cancelBubble = true;
window.event.returnValue = false;
return false; }}

This function is called on the onKeyDown event and it seems to work!

Q: When creating a form, how can I check to see if data entered in a text field contains all numerics?

Q: How do I get a word count of the text in a textarea?

Q: When a page reloads (due to the user pressing back) how do I clear a form of all the user entered data?

Simply invoke the form's reset method, immediately after defining the form, for example:

Q: How can I extract just the extension file name from a forms file upload field?

Q: How can I check where a visitor has come from?

Q: How can you make a .wav play when you click on an image?

You should use the tag.

The following will play the midi or wav file as soon as its loaded on a Java enabled browser:

The following allows you control when it plays:

You can replace sound.wav with sound.mid.

Q: When I open a new window, how can I change the contents of the original window from the new window?

Within the original window:

Within the new window:

load document into opener

load document

Q: How do I open a window at a given position on the screen?
In Netscape Navigator 4 the screenX and screenY attributes were introduced. In Internet Explorer 4 the top and left attributes were introduced. By combining the two both Netscape Navigator 4 and Internet Explorer 4 will allow you to position the window:

Q: Is it possible to close the parent window (main web browser window) from a child window?

Put the following in the child:

Although you'll need to make sure that the opener has been defined for browsers that don't have it by default, by placing the following in the parent:

Note, that this will likely prompt the user for confirmation before closing the window.

Q: How can I close a popup window after, say, 5 seconds?


Q: How do you return the results from a query into a new window?

Q: Is it possible to disallow a pop-up window to be maximized?

When opening a window use the attribute resizable:'apage.html','myWIndow','resizable=no');

The code does not work in Internet Explorer - you can maximise the window, and the resizable=no is ignored once you restore the size.

Q: Can i get Javascript counter?

JavaScript CAN NOT do a Web page counter alone. You will have to use a CGI script, or Java as well. The reason for this is that JavaScript can not write to external files, something necessary to run a counter (updating hit count).

Q: How do i clear the user's cache?
There are several things that can't be done with JavaScript for security reasons, including such things as changing user preferences or clearing the cache.

However, I do have a slick workaround that prevents a page from being stored in the user's cache. (You don't have to clear the cache if the page isn't in the cache!) Anyways, on with it. The code to stick in the HEAD section of your page is this:

Note: The second 'Expires' tag is not necessary for all browsers, but some browsers do use with the 'no-cache' tag, so it is best to just leave it in for good measure.



My Blog List