Welcome to the amazing dot net programming

Author: Vijaya Kumar
Contact:

    

  

Get updates by e-mail

HP Computer Museum

 

 

 

 

free website submission search engine seo optimization

 

Powered by Blogger

October 12, 2006

Javascript FAQ

Here i added the Javascript faq which i got some other resources, as a developer i know the importance of javascript in web development. Hope this faq would be helpful.

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 (<!--). Note that the JavaScript interpreter ignores the closing characters of HTML comments (-->). Consider this example:
<!-- This is treated as a one-line JS comment
<!-- It works just like a comment beginning with //
<!-- --> 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 <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:
<script language="JavaScript">
<!--

2) At the end of your script, put the following two lines:
//-->
</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>

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

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:

<SCRIPT LANGUAGE="JavaScript" SRC="myscript.js"></SCRIPT>

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

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

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

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

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 top.name (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.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'

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, <A HREF="mySound.mid">

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:

<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() .

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.

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:

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

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:

<INPUT type="radio" name="myButton" value="theValue" onClick="this.checked=false; alert('Sorry, this option is not available!')">

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

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:

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

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:

<body oncontextmenu="return false;">

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:

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

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

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

<script language="JavaScript">
<!--
var today = new Date();
var number = today.getDay() + 1;
document.write('<img src="images/' + number + '.jpg"'+'>');
//-->
</script>

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:

<script>
<!--
rnd.today=new Date();
rnd.seed=rnd.today.getTime();

function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280;
return rnd.seed/(233280.0);
};

function rand(number) {
return Math.ceil(rnd()*number);
};

// end central randomizer. -->
</SCRIPT>

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?
Answer:

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:

<script language="JavaScript">
<!--
if (document.images)
location.replace('http://www.somewhere.com/apage.html');
else
location.href = 'apage.html';
//-->
</script>

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:

<script langauge="JavaScript">
<!--
function newWindow(fileName,windowName) {
msgWindow=window.open(fileName,windowName);
}
//-->
</script>

<a href="javascript:newWindow('1.html','window1')">Open Window</a>

In the next window:

<script language="JavaScript">
<!--
function newWindow(fileName,windowName)
{ msgWindow=window.open(fileName,windowName); }

function replaceURL(fileName) { newWindow(fileName,'window2'); self.close();
}
//-->
</script>

<a href="javascript:replaceURL('2.html')">change location</a>

3) You can open a window without a toolbar:

<script language="JavaScript">
<!--
msgWindow=window.open('apage.html','windowName','toolbar=no');
//-->
</script>

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?
A:
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?
Answer:
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:

<script language="JavaScript">
<!--
function go(url) {
if (document.images)
location.replace(url);
else
location.href = url;
}
//-->
</script>

And then for all your links in that window:

<a href="javascript:go('http://somewhere.com/nextpage.html')">Next Page</a>

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?
A:
Sorry, not possible.

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

<script language="JavaScript">
<!--
function y2k(number) {
return (number < 1000) ? number + 1900 :
number; }

function daysElapsed(date1,date2) {
var difference = Date.UTC(y2k(date1.getYear()), date1.getMonth(),date1.getDate(),0,0,0) - Date.UTC(y2k(date2.getYear()), date2.getMonth(),date2.getDate(),0,0,0);

return difference/1000/60/60/24;}

document.write(daysElapsed(new Date(2000,0,1), new Date(1999,11,31)));
//-->
</script>

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

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

<SCRIPT LANGUAGE = 'JavaScript'>
<!--
function y2k(number) {
return (number < 1000) ? number + 1900 : number;
}

var date = new Date();
var date = new Date(Date.UTC(y2k(date.getYear()), date.getMonth(),date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()) - 5*60*60*1000);
document.write(date);
//-->
</SCRIPT>

Q: How can I calculate the difference between two dates?
Answer:
<script language="JavaScript">
<!--
function timeDifference(laterdate,earlierdate) {
var difference = laterdate.getTime() - earlierdate.getTime();
var daysDifference = Math.floor(difference/1000/60/60/24);
difference -= daysDifference*1000*60*60*24
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var secondsDifference = Math.floor(difference/1000);

document.write('difference = ' + daysDifference + ' day/s ' + hoursDifference + ' hour/s ' + minutesDifference + ' minute/s ' + secondsDifference + ' second/s ');}

var laterdate = new Date(2000,0,1); // 1st January 2000
var earlierdate = new Date(1998,2,13); // 13th March 1998
timeDifference(laterdate,earlierdate);
//-->
</script>

Q: How can I calculate the number of days in the current month?
A:
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?
Answer:
The date foramt has to be altered to:

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

<script language="JavaScript">
<!--
var textdate = 'Wed Aug 26 14:40:45 MET DST 1998.';
var myArray = textdate.split(' ');
var input = myArray[0] + ', ' + myArray[2] + ' ' + myArray[1] + ' ' + myArray[3] + ' ' + myArray[6].substring(0,4);
var output = Date.parse(input);
var mydate = new Date(output)
//-->
</script>

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

<script language="JavaScript">
<!--
var mmddyy = "12/31/99";
alert(mmddyy)
var mm = mmddyy.substring(0,2);
var dd = mmddyy.substring(3,5);
var yy = mmddyy.substring(6,8);
var ddmmyy = dd + '/' + mm + '/' + yy;
alert(ddmmyy);

// and back again...

var dd = ddmmyy.substring(0,2);
var mm = ddmmyy.substring(3,5);
var yy = ddmmyy.substring(6,8);
mmddyy = mm + '/' + dd + '/' + yy;
alert(mmddyy);
//-->
</script>

Q: How do I add a number of days to a date?
Answer:
<script language="JavaScript">
<!--
function addDays(myDate,days) {
return new Date(myDate.getTime() + days*24*60*60*1000);
}
alert(addDays(new Date(),10));
//-->
</script>

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

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?
A:

<script language="JavaScript">
<!--
function validate(string) {
if (!string) return false;
var Chars = "0123456789";
for (var i = 0; i < string.length; i++) {
if (Chars.indexOf(string.charAt(i)) == -1)
return false;
}
return true;
}
//--></script>

<form>
<input type="text" onChange="if (!validate(this.value)) alert('Not Valid')">
</form>

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

<script language="JavaScript">
<!--
function wordcount(string) {
var a = string.split(/\s+/g); // split the sentence into an array of words return a.length;
}
//-->
</script>

<form name="myForm">
<textarea name="myText" rows="3" cols="40">

This is some sample text. There is punctuation (sprinkled)about, plus some line-separators. The answer should be 19.
<form>
<input type="button" value="Word Count" onClick="alert(wordcount(this.form.myText.value))">
</form>

Q: How can I stop a user from hitting the Submit button twice?
Answer:

<form onSubmit="if (this.submitted) return false; this.submitted = true; return true">
<input type="submit">
</form>

Q: there a way to restrict number of characters within a textarea?
Answer:

<form> <textarea onKeyUp="if (this.value.length > 100) { alert('100 chars max'); this.value = this.value.substring(0,99); }"></textarea> </form>

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

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

<form name="myForm">
<input type="text">
</form>

<script language="JavaScript">
<!--
document.myForm.reset();
//-->
</script>

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

<html>
<head>
<script language="JavaScript">
<!--
function getExtension(value) {
return value.substring(value.lastIndexOf('.') + 1,value.length);
}
//-->
</script>
</head>
<body>
<form>
<input name="myFile" type="file">
<input type="button" value="Extract" onClick="alert(getExtension(this.form.myFile.value))">
</form>
</body>
</html>

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

<script language="JavaScript">
<!--
if (document.referrer != '')
document.write('You came from: ' + document.referrer);
//-->
</script>

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

You should use the <EMBED> 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:

<html>
<body>
<script language="JavaScript">
<!--
function playSound() {
document.firstSound.play();
}
function pauseSound() {
document.firstSound.pause();
}
function stopSound() {
document.firstSound.stop();
}
//-->
</script>
<a href="javascript:playSound()">
<img src="play.gif" width="100" hight="100">
</a>
<br>
<a href="javascript:pauseSound()">
<img src="pause.gif" width="100" hight="100">
</a>
<br>
<a href="javascript:stopSound()">
<img src="stop.gif" width="100" hight="100">
</a>
<br>
<embed src="sound.wav" hidden=true autostart=false loop=false name="firstSound" mastersound></body>
</html>

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?
A:

Within the original window:

<script language="JavaScript">
<!--
function newWindow(file,window) {
msgWindow=open(file,window,'resizable=no,width=200,height=200');
if (msgWindow.opener == null) msgWindow.opener = self;
}
//-->
</script>

<form>
<input type="button" value="Open New Window" onClick="newWindow('a.html','window2')">
</form>

Within the new window:

<script language="JavaScript">
<!--
function load(file,target) {
if (target != '')
target.window.location.href = file;
else
window.location.href = file;
}
//-->
</script>

<a href="javascript:load('b.html',top.opener)">load document into opener</a>
<p>
<a href="javascript:load('b.html','')">load document</a>

Q: How do I open a window at a given position on the screen?
A:
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:

<script language="JavaScript">
<!--
function openWindow() {
msgWindow = window.open('','newWin','width=100, height=100, screenX=400, screenY=400, top=400, left=400'); msgWindow.location.href = 'apage.html';}
//-->
</script>

<form>
<input type="button" onClick="openWindow()" value="Click Me">
</form>

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

Put the following in the child:

<script langauge="JavaScript">
<!--
opener.close();
//-->
</script>

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:

<script language="JavaScript">
<!--
msgWindow=open('',window,'resizable=no,width=200,height=200');
msgWindow.location.href ='apage.html';
if (msgWindow.opener == null) msgWindow.opener = self;
//-->
</script>

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?
A:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--setTimeout('self.close()',5000);
//-->
</SCRIPT>
<HEAD>
<BODY>...
</BODY>
</HTML>

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

<FORM ACTION="apage.html" TARGET="newwindow">
<INPUT TYPE="SUBMIT">
</FORM>

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

When opening a window use the attribute resizable:

window.open('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?
A:

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?
A:
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:

<META HTTP-EQUIV="pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="Thu, 01 Dec 1994 120000 GMT">

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.

Google
 
Web dotnetlibrary.blogspot.com