Top Banner
AVERAGE OF NUMBERS < SCRIPT>function sumDigits(num) { var i, sum = 0; // can declare two variables at once for (i = 1; i <= num; i++) { sum += i; // add each number to sum (ie, 1 + 2 + ... + num) } // Display result alert("The sum of the digits from 1 to "+ num + " is:\n\n\t " + sum); }</SCRIPT> <BODY> Looping Functions - Calculate the sum of the digits. <FORM NAME="SumNums"> The sum of the digits from 1 to: <INPUT TYPE="text" NAME="charNum"> <INPUT TYPE="button" VALUE="Calculate" onClick="sumDigits(SumNums.charNum.value)"> </FORM> NOTE: sumDigits() brute forces the answers, the Mathematical approach would be to use the Formula:n (n + 1) / 2. A Personal Counter To create your own personal visit counter, copy the cookie function script from the functions page and paste it in the <HEAD>...</HEAD> portion of your HTML document. Once you do that, you can embed a script that employs the universal cookie functions in your document. Take a look at the following script: <SCRIPT> var visits = getCookie("counter"); if (visits) { visits = parseInt(visits) + 1; document.write("By the way, you have been here " + visits + " times."); } else { visits = 1; document.write("By the way, this is your first time here."); } setCookie("counter", visits);
57

Javascript Programs Only

Dec 03, 2014

Download

Documents

Lokesh Verma

indian students born to lead- facebook(Lokesh verma)
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Javascript Programs Only

AVERAGE OF NUMBERS<SCRIPT>function sumDigits(num) {     var i, sum = 0;                  // can declare two variables at oncefor (i = 1; i <= num; i++) {             sum += i;              // add each number to sum (ie, 1 + 2 + ...+ num)     }  // Display result     alert("The sum of the digits from 1 to "+ num + " is:\n\n\t " + sum);}</SCRIPT> <BODY>

Looping Functions - Calculate the sum of the digits.

<FORM NAME="SumNums">     The sum of the digits from 1 to:     <INPUT TYPE="text" NAME="charNum"> <INPUT TYPE="button" VALUE="Calculate"       onClick="sumDigits(SumNums.charNum.value)"></FORM>

NOTE: sumDigits() brute forces the answers, the Mathematical approach would be to use the Formula:n (n + 1) / 2.

A Personal CounterTo create your own personal visit counter, copy the cookie function script from the functions page and paste it in the <HEAD>...</HEAD> portion of your HTML document. Once you do that, you can embed a script that employs the universal cookie functions in your document. Take a look at the following script:

<SCRIPT>

var visits = getCookie("counter");

if (visits) {     visits = parseInt(visits) + 1;     document.write("By the way, you have been here " + visits + " times.");}else {     visits = 1;     document.write("By the way, this is your first time here.");}

setCookie("counter", visits);

</SCRIPT>

Note that this script can be placed anywhere on the page. It prints the number of times the user has visited your site.

Status Bar Digital Clock

Check out the Time in the Status Line at the bottom left. This example is almost identical to the time example we saw when we looked at when we discussed the ternary operator. (Previous Example explained)

<SCRIPT>

Page 2: Javascript Programs Only

function showTime() {        var now = new Date();        var hours = now.getHours();        var minutes = now.getMinutes();        var seconds = now.getSeconds();

        var timeStr = "" + ((hours > 12) ? hours - 12 : hours);

        timeStr += ((minutes < 10) ? ":0" : ":") + minutes;        timeStr += ((seconds < 10) ? ":0" : ":") + seconds;        timeStr += (hours >= 12) ? " P.M." : " A.M.";

        status = timeStr; // time is displayed in the Status Line

        setTimeout("showTime()", 1000);}

</SCRIPT>

<BODY onLoad="showTime()">

Today is Tuesday, December 13.<SCRIPT>

var dayName = new Array ("Sunday", "Monday", "Tuesday", "Wednesday",                                              "Thursday", "Friday", "Saturday");

var monthName = new Array ("January", "February", "March", "April", "May",                                                  "June", "July", "August", "September", "October",                                                  "November", "December");

var now = new Date(); </SCRIPT><BODY><SCRIPT>

// getDay() -- day of the week (a number between 0 - 6)// getMonth() -- month of the year (a number between 0 - 11)// getDate() -- day of the month (a number between 1 - 31)document.write("<H1>Today is " +                          dayName[now.getDay()] + ", " +                          monthName[now.getMonth()] + " " +                          now.getDate() + ".</H1>")

</SCRIPT>

Event Handlers ExamplesAn Event Handler executes a segment of a code based on certain events occurring within the application, such as onLoad, onClick. JavaScript Event Handlers can be divided into two parts:

1. interactive Event Handlers and

2. non-interactive Event Handlers

An interactive Event Handler is the one that depends on the user interactivity with the form or the document.

Page 3: Javascript Programs Only

For example, onMouseOver is an interactive Event Handler because it depends on the users action with the mouse. On the other hand non-interactive Event Handler would be onLoad, because this Event Handler would automatically execute JavaScript code without the user's interactivity. Here are all the Event Handlers available in JavaScript:

EVENT HANDLER USED WITH

onAbort image

onBlur select, text, text area

onChange select, text, textarea

onClick button, checkbox, radio, link, reset, submit, area

onError image

onFocus select, text, textarea

onLoad windows, image

onMouseOut link, area

onMouseOver link, area

onSelect text, textarea

onSubmit form

onUnload window

onAbort:

An onAbort Event Handler executes JavaScript code when the user aborts loading an image.

See Example:

<HTML><HEAD><TITLE>Example of onAbort Event Handler</TITLE></HEAD>

<BODY><H3>Example of onAbort Event Handler</H3><B>Stop the loading of this image and see what happens:</B><P><IMG SRC="object.gif" onAbort="alert('You stopped the loading the image!')"></BODY></HTML>

Here, an alert() method is called using the onAbort Event Handler when the user aborts loading the image.

onBlur:

An onBlur Event Handler executes JavaScript code when input focus leaves the field of a text, textarea, or a select option. For windows, frames and framesets the Event Handler executes JavaScript code when the window loses focus. In windows you need to specify the Event Handler

Page 4: Javascript Programs Only

in the <BODY> attribute. For example:

<BODY BGCOLOR='#ffffff' onBlur="document.bgcolor='#000000'">

Note: On a Windows platform, the onBlur event does not work with <FRAMESET>.

See Example:<HTML><HEAD><TITLE>Example of onBlur Event Handler</TITLE><SCRIPT>

function validate(value) {    if (value < 0) alert("Please input a value that is greater or equal to 0");}

</SCRIPT></HEAD><BODY><H3> Example of onBlur Event Handler</H3>Try inputting a value less than zero:<BR><FORM>     <INPUT TYPE="text" onBlur="validate(this.value)"></FORM></BODY></HTML>

In this example, 'data' is a text field. When a user attempts to leave the field, the onBlur Event Handler calls the valid() function to confirm that 'data' has a legal value. Note that the keyword this is used to refer to the current object.

onChange:

The onChange Event Handler executes JavaScript code when input focus exits the field after the user modifies its text.

See Example:

<HTML><HEAD><TITLE>Example of onChange Event Handler</TITLE><SCRIPT>

function valid(input) {    alert("You have changed the value from 10 to " + input);}</SCRIPT>

</HEAD><BODY><H3>Example of onChange Event Handler</H3>Try changing the value from 10 to something else:<BR><FORM>    <INPUT TYPE="text" VALUE="10" onChange="valid(this.value)"> </FORM></BODY></HTML>

In this example, 'data' is a text field. When a user attempts to leave the field after a change of the original value, the onChange Event Handler calls the valid() function which alerts the user about value that has been inputted.

onClick:

In an onClick Event Handler, JavaScript function is called when an object in a button (regular, radio, reset and submit) is clicked, a link is pushed, a checkbox is checked or an image map area is selected. Except for the regular button and the area, the onClick Event Handler can return false to cancel the action. For example:

Page 5: Javascript Programs Only

<INPUT TYPE="submit" NAME="mysubmit" VALUE="Submit"   onClick="return confirm(`Are you sure you want to submit the form?')">

Note: On Windows platform, the onClick Event Handler does not work with reset buttons.

See Example:

<HTML><HEAD><TITLE>Example of onClick Event Handler</TITLE><SCRIPT>

function valid(form) {    var input = form.data.value;

    alert("Hello " + input + " ! Welcome...");}</SCRIPT></HEAD><BODY><H3> Example of onClick Event Handler </H3>Click on the button after inputting your name into the text box:<BR><FORM>     <INPUT TYPE="text" NAME="data">     <INPUT TYPE="button" VALUE="Click Here" onClick="valid(this.form)"></FORM></BODY></HTML>

In this example, when the user clicks the button "Click Here", the onClick Event Handler calls the function valid().

onError:

An onError Event Handler executes JavaScript code when an error occurs while loading a document or an image. With onError event now you can turn off the standard JavaScript error messages and have your own function that will trace all the errors in the script. To disable all the standard JavaScript error messages, all you need to do is set window.onerror = null. To call a function when an error occurs all you need to do is this: onError = "myerrorfunction()".

See Example:

<HTML><HEAD><TITLE>Example of onError Event Handler</TITLE>

<SCRIPT>window.onerror = ErrorSetting;

var e_msg = "";var e_file = "";var e_line = "";

document.form[8].value = "myButton"; // This is the error function ErrorSetting(msg, file_loc, line_no) {     e_msg = msg;     e_file = file_loc;     e_line = line_no;

   return true; }

function display() {

Page 6: Javascript Programs Only

     var   error_d = "Error in file: " + e_file +                               "\nline number:" + e_line +                              "\nMessage:" + e_msg;     alert("Error Window:\n" + error_d); }

</SCRIPT></HEAD><BODY><H3> Example of onError Event Handler </H3><FORM>     <INPUT TYPE="button" VALUE="Show the error" onClick="display()"></FORM></BODY></HTML>

Notice that the function ErrorSetting() takes three arguments: message text, URL and Line number of the error line. So all we did was invoke the function when an error occurred and set these values to three different variables. Finally, we displayed the values via an alert method.

Note: If you set the function ErrorSetting() to false, the standard dialog will be seen.

onFocus:

An onFocus Event Handler executes JavaScript code when input focus enters the field either by tabbing in or by clicking but not selecting input from the field. For windows, frames and framesets the Event Handler executes JavaScript code when the window gets focused. In windows you need to specify the Event Handler in the <BODY> attribute. For example:

<BODY BGCOLOR="#ffffff" onFocus="document.bgcolor='#000000'">

Note: On a Windows platform, the onFocus Event Handler does not work with <FRAMESET>.

See Example:

<HTML><HEAD><TITLE>Example of onFocus Event Handler</TITLE></HEAD>

<BODY><H3>Example of onFocus Event Handler</H3>Click your mouse in the text box:<BR><FORM>     <INPUT TYPE="text" onFocus='alert("You focused in the textbox!!")'></FORM></BODY></HTML>

In the above example, when you put your mouse on the text box, an alert() message displays a message.

onLoad:

An onLoad event occurs when a window or image finishes loading. For windows, this Event Handler is specified in the <BODY> attribute of the window. In an image, the Event Handler will execute handler text when the image is loaded. For example:

<IMG SRC="images/object.gif" NAME="jsobjects"    onLoad="alert('You loaded myimage')">

See Example:

Page 7: Javascript Programs Only

<HTML><HEAD><TITLE>Example of onLoad Event Handler</TITLE> <SCRIPT>

function hello() {    alert("Hello there...\n\nThis is an example of onLoad.");}</SCRIPT></HEAD><BODY onLoad="hello()"><H3>Example of onLoad Event Handler</H3></BODY></HTML>

The example shows how the function hello() is called by using the onLoad Event Handler.

onMouseOut:

JavaScript code is called when the mouse leaves a specific link or an object or area from outside that object or area. For area object the Event Handler is specified with the <AREA> tag.

See Example:

<HTML><HEAD><TITLE> Example of onMouseOut Event Handler </TITLE></HEAD><BODY><H3> Example of onMouseOut Event Handler </H3>Put your mouse over <A HREF="javascript:void('');"    onMouseOut="window.status='You left the link!'; return true;">here</A> and then take the mouse pointer away.</BODY></HTML>

In the above example, after pointing your mouse and leaving the link , the text "You left the link!" appears on your window's status bar.

onMouseOver:

JavaScript code is called when the mouse is placed over a specific link or an object or area from outside that object or area. For area object the Event Handler is specified with the <AREA> tag. For example:

<MAP NAME="mymap"><AREA NAME="FirstArea" COORDS="0,0,49,25" HREF="mylink.html"  onMouseOver="self.status='This will take you to mylink.html'; return true"></MAP>

See Example:

<HTML><HEAD><TITLE>Example of onMouseOver Event Handler</TITLE></HEAD><BODY><H3>Example of onMouseOver Event Handler</H3>Put your mouse over <A HREF="javascript:void('');"    onMouseOver="window.status='Hello! How are you?'; return true;"> here</A>and look at the status bar (usually at the bottom of your browser window).</BODY></HTML>

Page 8: Javascript Programs Only

In the above example when you point your mouse to the link, the text "Hello! How are you?" appears on your window's status bar.

onReset:

A onReset Event Handler executes JavaScript code when the user resets a form by clicking on the reset button.

See Example:

<HTML><HEAD><TITLE>Example of onReset Event Handler</TITLE></HEAD><BODY><H3> Example of onReset Event Handler </H3>Please type something in the text box and press the reset button:<BR><FORM onReset="alert('This will reset the form!')">     <INPUT TYPE="text">     <INPUT TYPE="reset" VALUE="Reset Form" ></FORM></BODY></HTML>

In the above example, when you push the button, "Reset Form" after typing something, the alert method displays the message, "This will reset the form!"

onSelect:

A onSelect Event Handler executes JavaScript code when the user selects some of the text within a text or textarea field.

See Example:

<HTML><HEAD><TITLE>Example of onSelect Event Handler</TITLE></HEAD><BODY><H3>Example of onSelect Event Handler</H3>Select the text from the text box:<br><FORM>     <INPUT TYPE="text" VALUE="Select This"       onSelect="alert('This is an example of onSelect!!')"></FORM></BODY></HTML>

In the above example, when you try to select the text or part of the text, the alert method displays the message, "This is an example of onSelect!!".

onSubmit:

An onSubmit Event Handler calls JavaScript code when the form is submitted.

See Example:

<HTML><HEAD><TITLE> Example of onSubmit Event Handler </TITLE></HEAD>

<BODY><H3>Example of onSubmit Event Handler </H3>Type your name and press the button<BR>

Page 9: Javascript Programs Only

<FORM NAME="myform" onSubmit="alert('Thank you ' + myform.data.value +'!')">     <INPUT TYPE="text" NAME="data">     <INPUT TYPE="submit" VALUE="Submit this form"></FORM></BODY><HTML>

In this example, the onSubmit Event Handler calls an alert() function when the button "Submit this form" is pressed.

onUnload:

An onUnload Event Handler calls JavaScript code when a document is exited.

See Example:

<HTML><HEAD><TITLE>onUnLoad Example</TITLE> <SCRIPT>

function goodbye() {        alert("Thanks for Visiting!");}</SCRIPT></HEAD>

<BODY onUnLoad="goodbye();"><H3>Example of onUnload Event Handler</H3>Look what happens when you try to leave this page...</BODY></HTML>

In this example, the onUnload Event Handler calls the Goodbye() function as user exits a document.

NOTE: You can also call JavaScript code via explicit Event Handler call. For example say you have a function called myfunction(). You could call this function like this:document.form.mybotton.onclick = myfunction

Notice that you don't need to put the () after the function and also the Event Handler has to be spelled out in lowercase.

US Missions to Mars

< Previous     Next ><SCRIPT>

var myPix = new Array("images/pathfinder.gif", "images/surveyor.gif", "images/surveyor98.gif");

Page 10: Javascript Programs Only

var thisPic = 0;

function processPrevious() {     if (document.images && thisPic > 0) {          thisPic--;          document.myPicture.src = myPix[thisPic];     }}

function processNext() {     if (document.images && thisPic < 2) {          thisPic++;          document.myPicture.src = myPix[thisPic];     }} </SCRIPT><IMG SRC="images/pathfinder.gif" NAME="myPicture">

<A HREF="javascript:processPrevious()">Previous</A><A HREF="javascript:processNext()">Next</A>How to use HTML Scripts on my website?First you need to open the page with a HTML editor such as dream weaver or front page or even note pad , notice that if you using any other page making (ASP, PHP , etc.) languages it doesn't matter. Just open it and access to source file. When you Open it, there are some codes in HTML called tags: you have to find something called "BODY" In HTML code it's like <BODY>  When you find it just skip a line and copy and paste after body tag the codes which we offered you in this website Anyways if you couldn't find that just paste the codes in the end of the source file.

Make your website as user's Homepage

<BODY><!-- this script got from www.javascriptfreecode.com coded by: Krishna Eydatoula--><SCRIPT LANGUAGE="JavaScript">

<!-- Begin// If it's Internet Explorer, use automatic link// Be sure to change the "http://www.YourWebSiteHere.com\"// to the URL you want them to bookmark.if (document.all){ document.write('<A HREF="javascript:history.go(0);"

onClick="this.style.behavior=\'url(#default#homepage)\';this.setHomePage(\'http://www.YourWebSiteHere.com\');">');

document.write('<font size="5" color=6699FF face=arial><B>Click Here to Make My Web Page Your Homepage</B></font></a>');

}

// If it's Netscape 6, tell user to drag link onto Home button// Be sure to change the "http://www.YourWebSiteHere.com\"// to the URL you want them to bookmark.else if (document.getElementById){

Page 11: Javascript Programs Only

document.write('<a href="http://www.YourWebSiteHere.com">Drag this link onto your Home button to make this your Home Page.</a>');

}

// If it's Netscape 4 or lower, give instructions to set Home Pageelse if (document.layers){ document.write('<b>Make this site your home page:</b><br>- Go to <b>Preferences</b> in the

<B>Edit</B> Menu.<br>- Choose <b>Navigator</b> from the list on the left.<br>- Click on the <b>"Use Current Page"</b> button.');

}

// If it's any other browser, for which I don't know the specifications of home paging, display instructionselse { document.write('<b>Make this site your home page:</b><br>- Go to <b>Preferences</b> in the

<B>Edit</B> Menu.<br>- Choose <b>Navigator</b> from the list on the left.<br>- Click on the <b>"Use Current Page"</b> button.');

}// End -->

</script><br /><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

A message box when page opens

<html><head><script language="javascript" type="text/javascript">alert("Welcome to my site")</script></head></html> <font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>Don't let the user use right click on mouse<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><SCRIPT LANGUAGE="JavaScript">var message="Function Disabled!";///////////////////////////////////function clickIE() {if (document.all) {alert(message);return false;}}function clickNS(e) {if (document.layers||(document.getElementById&&!document.all)) {if (e.which==2||e.which==3) {alert(message);return false;}}}if (document.layers) {document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}

document.oncontextmenu=new Function("return false")// --> </script><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Page 12: Javascript Programs Only

Make your scrollbar colorful<!-- this script got from www.javascriptfreecode.com coded by: Krishna Eydat--> <STYLE>BODY {SCROLLBAR-FACE-COLOR: red; SCROLLBAR-HIGHLIGHT-COLOR: gray;

SCROLLBAR-SHADOW-COLOR: black; SCROLLBAR-ARROW-COLOR: gray;

SCROLLBAR-TRACK-COLOR: black; SCROLLBAR-DARKSHADOW-COLOR: red}</STYLE>

<font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Search box ( Search engine ) for your page<!-- this script got from www.javascriptfreecode.com coded by: Krishna Eydat--><SCRIPT language=JavaScript>var NS4 = (document.layers); var IE4 = (document.all);var win = window; var n = 0;function findInPage(str) { var txt, i, found; if (str == "") return false; if (NS4) { if (!win.find(str)) while(win.find(str, false, true)) n++; else n++; if (n == 0) alert("Not found."); } if (IE4) { txt = win.document.body.createTextRange(); for (i = 0; i <= n && (found = txt.findText(str)) != false; i++) { txt.moveStart("character", 1); txt.moveEnd("textedit"); } if (found) { txt.moveStart("character", -1); txt.findText(str); txt.select(); txt.scrollIntoView(); n++; } else { if (n > 0) { n = 0; findInPage(str); } else alert("Sorry, we couldn't find.Try again"); } }

Page 13: Javascript Programs Only

return false;}</SCRIPT><FORM name=search onsubmit="return findInPage(this.string.value);"><P align=center><FONT size=3><INPUT style="BORDER-RIGHT: #666666 1px solid; BORDER-TOP: #666666 1px solid; FONT-SIZE: 8pt; BORDER-LEFT: #666666 1px solid; BORDER-BOTTOM: #666666 1px solid" onchange="n = 0;" size=16 name=string></FONT><BR><INPUT style="BORDER-RIGHT: #ffffff 1px solid; BORDER-TOP: #ffffff 1px solid; FONT-SIZE: 8pt; BORDER-LEFT: #ffffff 1px solid; BORDER-BOTTOM: #ffffff 1px solid; FONT-FAMILY: Tahoma; BACKGROUND-COLOR: #aaaaaa" type=submit value=Search in page ><center><font size=2pt;><font family=Times New Roman;><b>

<font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font><BR> </P></FORM></DIV><BR><!-- /Search-->

Raining on texts<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat -->

<body><SCRIPT LANGUAGE="JavaScript"><!-- Beginvar no = 50; var speed = 1;var ns4up = (document.layers) ? 1 : 0;var ie4up = (document.all) ? 1 : 0;var s, x, y, sn, cs;var a, r, cx, cy;var i, doc_width = 800, doc_height = 600;if (ns4up) {doc_width = self.innerWidth;doc_height = self.innerHeight;}elseif (ie4up) {doc_width = document.body.clientWidth;doc_height = document.body.clientHeight;}x = new Array();y = new Array(); r = new Array();cx = new Array(); cy = new Array();s = 8;for (i = 0; i < no; ++ i) {initRain();if (ns4up) {if (i == 0) {document.write("<layer name=\"dot"+ i +"\" left=\"1\" ");document.write("top=\"1\" visibility=\"show\"><font color=\"blue\">");document.write(",</font></layer>");

Page 14: Javascript Programs Only

}else {document.write("<layer name=\"dot"+ i +"\" left=\"1\" ");document.write("top=\"1\" visibility=\"show\"><font color=\"blue\">");document.write(",</font></layer>"); }}elseif (ie4up) {if (i == 0) {document.write("<div id=\"dot"+ i +"\" style=\"POSITION: ");document.write("absolute; Z-INDEX: "+ i +"; VISIBILITY: ");document.write("visible; TOP: 15px; LEFT: 15px;\"><font color=\"blue\">");document.write(",</font></div>");}else {document.write("<div id=\"dot"+ i +"\" style=\"POSITION: ");document.write("absolute; Z-INDEX: "+ i +"; VISIBILITY: ");document.write("visible; TOP: 15px; LEFT: 15px;\"><font color=\"blue\">");document.write(",</font></div>"); } }}function initRain() {a = 6;r[i] = 1; sn = Math.sin(a);cs = Math.cos(a);cx[i] = Math.random() * doc_width + 1;cy[i] = Math.random() * doc_height + 1;x[i] = r[i] * sn + cx[i];y[i] = cy[i];}function makeRain() {r[i] = 1;cx[i] = Math.random() * doc_width + 1;cy[i] = 1;x[i] = r[i] * sn + cx[i];y[i] = r[i] * cs + cy[i];}function updateRain() {r[i] += s;x[i] = r[i] * sn + cx[i];y[i] = r[i] * cs + cy[i];}function raindropNS() {for (i = 0; i < no; ++ i) {updateRain();if ((x[i] <= 1) || (x[i] >= (doc_width - 20)) || (y[i] >= (doc_height - 20))) {makeRain();

Page 15: Javascript Programs Only

doc_width = self.innerWidth;doc_height = self.innerHeight;}document.layers["dot"+i].top = y[i];document.layers["dot"+i].left = x[i];}setTimeout("raindropNS()", speed);}function raindropIE() {for (i = 0; i < no; ++ i) {updateRain();if ((x[i] <= 1) || (x[i] >= (doc_width - 20)) || (y[i] >= (doc_height - 20))) {makeRain();doc_width = document.body.clientWidth;doc_height = document.body.clientHeight;}document.all["dot"+i].style.pixelTop = y[i];document.all["dot"+i].style.pixelLeft = x[i];}setTimeout("raindropIE()", speed);}if (ns4up) {raindropNS();}elseif (ie4up) {raindropIE();}// End --></script></body><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Google search on web<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><!-- Search Google --><center><FORM method=GET action="http://www.google.com/search"><TABLE bgcolor="#FFFFFF"><tr><td><A HREF="http://www.google.com/"><IMG SRC="http://www.google.com/logos/Logo_40wht.gif" <br></A><INPUT TYPE=text name=q size=31 maxlength=255 value=""><INPUT TYPE=hidden name=hl value="en"><INPUT type=submit name=btnG VALUE="Google Search"></td></tr></TABLE></FORM></center><!-- Search Google -->

Page 16: Javascript Programs Only

<font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Stars moving in background<!-- this script got from www.javascriptfreecode.com--> <FONT face=Tahoma color=white> <html><head></head><body><!-- STEP ONE: Insert the onLoad event handler into your BODY tag --><BODY BGCOLOR="#000000" onLoad="fly()"><!-- STEP TWO: Paste this code into the BODY of your HTML document --><SCRIPT LANGUAGE="JavaScript"><!-- BeginSmallStars = 30; LargeStars = 10;SmallYpos = new Array();SmallXpos = new Array();LargeYpos = new Array();LargeXpos = new Array();Smallspeed= new Array();Largespeed= new Array();ns=(document.layers)?1:0;if (ns) {for (i = 0; i < SmallStars; i++) {document.write("<LAYER NAME='sn"+i+"' LEFT=0 TOP=0 BGCOLOR='#FFFFF0' CLIP='0,0,1,1'></LAYER>");}for (i = 0; i < LargeStars; i++) {document.write("<LAYER NAME='ln"+i+"' LEFT=0 TOP=0 BGCOLOR='#FFFFFF' CLIP='0,0,2,2'></LAYER>"); }}else {document.write('<div style="position:absolute;top:0px;left:0px">');document.write('<div style="position:relative">');for (i = 0; i < SmallStars; i++) {document.write('<div id="si" style="position:absolute;top:0;left:0;width:1px;height:1px;background:#fffff0;font-size:1px"></div>');}document.write('</div>');document.write('</div>');document.write('<div style="position:absolute;top:0px;left:0px">');document.write('<div style="position:relative">');for (i = 0; i < LargeStars; i++) {document.write('<div id="li" style="position:absolute;top:0;left:0;width:2px;height:2px;background:#ffffff;font-size:2px"></div>');}document.write('</div>');document.write('</div>');}

Page 17: Javascript Programs Only

WinHeight = (document.layers)?window.innerHeight:window.document.body.clientHeight;WinWidth = (document.layers)?window.innerWidth:window.document.body.clientWidth;for (i = 0; i < SmallStars; i++) {SmallYpos[i] = Math.round(Math.random() * WinHeight);SmallXpos[i] = Math.round(Math.random() * WinWidth);Smallspeed[i]= Math.random() * 5 + 1;}for (i = 0; i < LargeStars; i++) {LargeYpos[i] = Math.round(Math.random() * WinHeight);LargeXpos[i] = Math.round(Math.random() * WinWidth);Largespeed[i] = Math.random() * 10 + 5;}function fly() {var WinHeight = (document.layers)?window.innerHeight:window.document.body.clientHeight;var WinWidth = (document.layers)?window.innerWidth:window.document.body.clientWidth;var hscrll = (document.layers)?window.pageYOffset:document.body.scrollTop;var wscrll = (document.layers)?window.pageXOffset:document.body.scrollLeft;for (i = 0; i < LargeStars; i++) {LargeXpos[i] -= Largespeed[i];if (LargeXpos[i] < -10) {LargeXpos[i] = WinWidth;LargeYpos[i] = Math.round(Math.random() * WinHeight);Largespeed[i] = Math.random() * 10 + 5;}if (ns) {document.layers['ln'+i].left = LargeXpos[i];document.layers['ln'+i].top = LargeYpos[i] + hscrll;}else {li[i].style.pixelLeft = LargeXpos[i];li[i].style.pixelTop = LargeYpos[i] + hscrll; }}for (i = 0; i < SmallStars; i++) {SmallXpos[i] -= Smallspeed[i];if (SmallXpos[i] < -10) {SmallXpos[i] = WinWidth;SmallYpos[i] = Math.round(Math.random()*WinHeight);Smallspeed[i] = Math.random() * 5 + 1;}if (ns) {document.layers['sn'+i].left = SmallXpos[i];document.layers['sn'+i].top = SmallYpos[i]+hscrll;}else {si[i].style.pixelLeft = SmallXpos[i];si[i].style.pixelTop = SmallYpos[i]+hscrll; } }

Page 18: Javascript Programs Only

setTimeout('fly()', 10);}// End --></script><!-- Script Size: 3.79 KB --></body></html><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Fall leaves<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><script language="JavaScript1.2">

//Pre-load your image below!grphcs=new Array(6)Image0=new Image();Image0.src=grphcs[0]="http://javascriptfreecode.com/images/barg.gif";Image1=new Image();Image1.src=grphcs[1]="http://javascriptfreecode.com/images/barg.gif"Image2=new Image();Image2.src=grphcs[2]="http://javascriptfreecode.com/images/barg.gif"Image3=new Image();Image3.src=grphcs[3]="http://javascriptfreecode.com/images/barg.gif"Image4=new Image();Image4.src=grphcs[4]="http://javascriptfreecode.com/images/barg.gif"Image5=new Image();Image5.src=grphcs[5]="http://javascriptfreecode.com/images/barg.gif"

Amount=8; //Smoothness depends on image file size, the smaller the size the more you can use!Ypos=new Array();Xpos=new Array();Speed=new Array();Step=new Array();Cstep=new Array();ns=(document.layers)?1:0;ns6=(document.getElementById&&!document.all)?1:0;

if (ns){for (i = 0; i < Amount; i++){var P=Math.floor(Math.random()*grphcs.length);rndPic=grphcs[P];document.write("<LAYER NAME='sn"+i+"' LEFT=0 TOP=0><img src="+rndPic+"></LAYER>");}}else{document.write('<div style="position:absolute;top:0px;left:0px"><div style="position:relative">');for (i = 0; i < Amount; i++){var P=Math.floor(Math.random()*grphcs.length);rndPic=grphcs[P];document.write('<img id="si'+i+'" src="'+rndPic+'" style="position:absolute;top:0px;left:0px">');}

Page 19: Javascript Programs Only

document.write('</div></div>');}WinHeight=(ns||ns6)?window.innerHeight:window.document.body.clientHeight;WinWidth=(ns||ns6)?window.innerWidth-70:window.document.body.clientWidth;for (i=0; i < Amount; i++){ Ypos[i] = Math.round(Math.random()*WinHeight); Xpos[i] = Math.round(Math.random()*WinWidth); Speed[i]= Math.random()*5+3; Cstep[i]=0; Step[i]=Math.random()*0.1+0.05;}function fall(){var WinHeight=(ns||ns6)?window.innerHeight:window.document.body.clientHeight;var WinWidth=(ns||ns6)?window.innerWidth-70:window.document.body.clientWidth;var hscrll=(ns||ns6)?window.pageYOffset:document.body.scrollTop;var wscrll=(ns||ns6)?window.pageXOffset:document.body.scrollLeft;for (i=0; i < Amount; i++){sy = Speed[i]*Math.sin(90*Math.PI/180);sx = Speed[i]*Math.cos(Cstep[i]);Ypos[i]+=sy;Xpos[i]+=sx; if (Ypos[i] > WinHeight){Ypos[i]=-60;Xpos[i]=Math.round(Math.random()*WinWidth);Speed[i]=Math.random()*5+3;}if (ns){document.layers['sn'+i].left=Xpos[i];document.layers['sn'+i].top=Ypos[i]+hscrll;}else if (ns6){document.getElementById("si"+i).style.left=Math.min(WinWidth,Xpos[i]);document.getElementById("si"+i).style.top=Ypos[i]+hscrll;}else{eval("document.all.si"+i).style.left=Xpos[i];eval("document.all.si"+i).style.top=Ypos[i]+hscrll;} Cstep[i]+=Step[i];}setTimeout('fall()',20);}window.onload=fall//--></script><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Javascript Code: Text alert for enter and exit<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat -->

Page 20: Javascript Programs Only

<html><head><script language="javascript" type="text/javascript">

alert("Welcome to my weblog")</script></head><body><h1><!-- hide script from old browsers --><!--this is on example of a long JavaScript comment--><script language="javascript" type="text/javascript">document.write("IranJavaScript")//end hiding script from old browsers --></script></h1></body></html><!-- DESCRIPTION: This will cause an elert message before your visitor leaves (OR reloads) your page.

INSTRUCTIONS: Place this tag where your BODY tag is. Make changes to attributes (TEXT, LINK, VLINK, BGCOLOR, etc.) as necessary.

FUNCTIONALITY: Works in both Netscape and IE.

//Modified by CoffeeCup Software //This code is Copyright (c) 1997 CoffeeCup Software //all rights reserved. License is granted to a single user to //reuse this code on a personal or business Web Site. --><BODY onUnload="window.alert(' Good Bye ')"></BODY><!-- DESCRIPTION: This will cause an elert message before your visitor leaves (OR reloads) your page.

INSTRUCTIONS: Place this tag where your BODY tag is. Make changes to attributes (TEXT, LINK, VLINK, BGCOLOR, etc.) as necessary.

FUNCTIONALITY: Works in both Netscape and IE.

//Modified by CoffeeCup Software //This code is Copyright (c) 1997 CoffeeCup Software //all rights reserved. License is granted to a single user to //reuse this code on a personal or business Web Site. -->

<BODY onUnload="window.alert(' Good Bye ')"></BODY><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Javascript Code: Moving text status<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><BODY onLoad="timerONE=window.setTimeout('slide(120,0)',20);"><SCRIPT LANGUAGE="JavaScript">function slide(jumpSpaces,position) { var msg = "This JavaScript will slide in your desired message....Cool...isn't it???.......drink more coffee"

Page 21: Javascript Programs Only

var out = "" if (endScroll) {return false} for (var i=0; i<position; i++) {out += msg.charAt(i)} for (i=1;i<jumpSpaces;i++) {out += " "} out += msg.charAt(position) window.status = out if (jumpSpaces <= 1) { position++ if (msg.charAt(position) == ' ') {position++ } jumpSpaces = 100-position } else if (jumpSpaces > 3) {jumpSpaces *= .75} else {jumpSpaces--} if (position != msg.length) { var cmd = "slide(" + jumpSpaces + "," + position + ")"; scrollID = window.setTimeout(cmd,5); } else { scrolling = false return false } return true }function ccSetup() { if (scrolling) if (!confirm('Re-initialize slide?')) return false endScroll = true scrolling = true var killID = window.setTimeout('endScroll=false',6) scrollID = window.setTimeout('slide(100,0)',10) return true }var scrollID = Objectvar scrolling = falsevar endScroll = false</SCRIPT><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>For loop<html><body><script type="text/javascript">for (i = 1; i <= 6; i++){document.write("<h" + i + ">This is heading " + i);document.write("</h" + i + ">");}</script></body></html>

Page 22: Javascript Programs Only

Looping through HTML headers<html><body><script type="text/javascript">for (i = 1; i <= 6; i++){document.write("<h" + i + ">This is heading " + i);document.write("</h" + i + ">");}</script></body></html>

While loop<html><body><script type="text/javascript">i=0;while (i<=5){document.write("The number is " + i);document.write("<br />");i++;}</script><p>Explanation:</p><p><b>i</b> is equal to 0.</p><p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p><p><b>i</b> will increase by 1 each time the loop runs.</p></body></html>Do While loop<html><body><script type="text/javascript">i=0;while (i<=5){document.write("The number is " + i);document.write("<br />");i++;}</script><p>Explanation:</p><p><b>i</b> is equal to 0.</p><p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p><p><b>i</b> will increase by 1 each time the loop runs.</p></body></html>

Break a loop<html><body><script type="text/javascript">var i=0;for (i=0;i<=10;i++){

Page 23: Javascript Programs Only

if (i==3) { break; }document.write("The number is " + i);document.write("<br />");}</script><p>Explanation: The loop will break when i=3.</p></body></html>

Break and continue a loop<html><body><script type="text/javascript">var i=0;for (i=0;i<=10;i++){if (i==3) { continue; }document.write("The number is " + i);document.write("<br />");}</script><p>Explanation: The loop will break the current loop and continue with the next value when i=3.</p></body></html>

Use a for...in statement to loop through the elements of an object<html><body><script type="text/javascript">var person={fname:"John",lname:"Doe",age:25}; for (x in person){document.write(person[x] + " ");}</script></body></html>

Set background color (User control)<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><p>[<a href="/"onmouseover="document.bgColor='green'">Green</a>]<br>[<a href="/"onmouseover="document.bgColor='greem'">Bright Green</a>]<br>[<a href="/"onmouseover="document.bgColor='seagreen'">Sea Green</a>]<br>[<a href="/"onmouseover="document.bgColor='red'">Red</a>]<BR>[<a href="/"onmouseover="document.bgColor='magenta'">Magenta</a>]<br>[<a href="/"onmouseover="document.bgColor='fusia'">Fusia</a>]<br>

Page 24: Javascript Programs Only

[<a href="/"onmouseover="document.bgColor='pink'">Pink</a>]<br>[<a href="/"onmouseover="document.bgColor='purple'">Purple</a>]<BR>[<a href="/"onmouseover="document.bgColor='navy'">Navy</a>]<br>[<a href="/"onmouseover="document.bgColor='blue'">Blue</a>]<br>[<a href="/"onmouseover="document.bgColor='royalblue'">Royal Blue</a>]<br>[<a href="/"onmouseover="document.bgColor='Skyblue'">Sky Blue</a>]<BR>[<a href="/"onmouseover="document.bgColor='yellow'">Yellow</a>]<br>[<a href="/"onmouseover="document.bgColor='brown'">Brown</a>]<br>[<a href="/"onmouseover="document.bgColor='almond'">Almond</a>]<br>[<a href="/"onmouseover="document.bgColor='white'">White</a>]<BR>[<a href="/"onmouseover="document.bgColor='black'">Black</a>]<br>[<a href="/"onmouseover="document.bgColor='coral'">Coral</a>]<br>[<a href="/"onmouseover="document.bgColor='olivedrab'">Olive Drab</a>]<br>[<a href="/"onmouseover="document.bgColor='orange'">Orange</a>]<br><hr color="#00FFFF"><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Back and forward button <!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><!-- Start of Back/Forward Buttons Script--><!-- Instructions: Just put this script anywhere on your webpage

and you will give your visitor 2 Back and Forward Navigationbuttons. Designed for websites that have multiple webpages.

--><SCRIPT LANGUAGE="JavaScript"> <!-- hide this script tag's contents from old browsersfunction goHist(a) { history.go(a); // Go back one.}//<!-- done hiding from old browsers --></script><FORM METHOD="post"><INPUT TYPE="button" VALUE=" BACK " onClick="goHist(-1)"><INPUT TYPE="button" VALUE="FORWARD" onClick="goHist(1)"></form>

Page 25: Javascript Programs Only

<!-- End of Back/Forward Buttons Script --><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Calculator script<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><CENTER><FORM name="Keypad" action=""><TABLE><B><TABLE border=2 width=50 height=60 cellpadding=1 cellspacing=5><TR><TD colspan=3 align=middle><input name="ReadOut" type="Text" size=24 value="0" width=100%></TD><TD</TD><TD><input name="btnClear" type="Button" value=" C " onclick="Clear()"></TD><TD><input name="btnClearEntry" type="Button" value=" CE " onclick="ClearEntry()"></TD></TR><TR><TD><input name="btnSeven" type="Button" value=" 7 " onclick="NumPressed(7)"></TD><TD><input name="btnEight" type="Button" value=" 8 " onclick="NumPressed(8)"></TD><TD><input name="btnNine" type="Button" value=" 9 " onclick="NumPressed(9)"></TD><TD></TD><TD><input name="btnNeg" type="Button" value=" +/- " onclick="Neg()"></TD><TD><input name="btnPercent" type="Button" value=" % " onclick="Percent()"></TD></TR><TR><TD><input name="btnFour" type="Button" value=" 4 " onclick="NumPressed(4)"></TD><TD><input name="btnFive" type="Button" value=" 5 " onclick="NumPressed(5)"></TD><TD><input name="btnSix" type="Button" value=" 6 " onclick="NumPressed(6)"></TD><TD></TD><TD align=middle><input name="btnPlus" type="Button" value=" + " onclick="Operation('+')"></TD><TD align=middle><input name="btnMinus" type="Button" value=" - " onclick="Operation('-')"></TD></TR><TR><TD><input name="btnOne" type="Button" value=" 1 " onclick="NumPressed(1)"></TD><TD><input name="btnTwo" type="Button" value=" 2 " onclick="NumPressed(2)"></TD><TD><input name="btnThree" type="Button" value=" 3 " onclick="NumPressed(3)"></TD><TD></TD><TD align=middle><input name="btnMultiply" type="Button" value=" * " onclick="Operation('*')"></TD><TD align=middle><input name="btnDivide" type="Button" value=" / " onclick="Operation('/')"></TD></TR><TR><TD><input name="btnZero" type="Button" value=" 0 " onclick="NumPressed(0)">

Page 26: Javascript Programs Only

</TD><TD><input name="btnDecimal" type="Button" value=" . " onclick="Decimal()"></TD><TD colspan=3></TD><TD><input name="btnEquals" type="Button" value=" = " onclick="Operation('=')"></TD></TR></TABLE></TABLE></B></FORM></CENTER><font face="Verdana, Arial, Helvetica" size=2><SCRIPT LANGUAGE="JavaScript"><!-- Beginvar FKeyPad = document.Keypad;var Accumulate = 0;var FlagNewNum = false;var PendingOp = "";function NumPressed (Num) {if (FlagNewNum) {FKeyPad.ReadOut.value = Num;FlagNewNum = false; }else {if (FKeyPad.ReadOut.value == "0")FKeyPad.ReadOut.value = Num;elseFKeyPad.ReadOut.value += Num; }}function Operation (Op) {var Readout = FKeyPad.ReadOut.value;if (FlagNewNum && PendingOp != "=");else{FlagNewNum = true;if ( '+' == PendingOp )Accumulate += parseFloat(Readout);else if ( '-' == PendingOp )Accumulate -= parseFloat(Readout);else if ( '/' == PendingOp )Accumulate /= parseFloat(Readout);else if ( '*' == PendingOp )Accumulate *= parseFloat(Readout);elseAccumulate = parseFloat(Readout);FKeyPad.ReadOut.value = Accumulate;PendingOp = Op;

Page 27: Javascript Programs Only

}}function Decimal () { var curReadOut = FKeyPad.ReadOut.value;if (FlagNewNum) { curReadOut = "0.";FlagNewNum = false; }else{if (curReadOut.indexOf(".") == -1)curReadOut += "."; }FKeyPad.ReadOut.value = curReadOut;}function ClearEntry () { FKeyPad.ReadOut.value = "0";FlagNewNum = true;}function Clear () { Accumulate = 0; PendingOp = "";ClearEntry();}function Neg () {FKeyPad.ReadOut.value = parseFloat(FKeyPad.ReadOut.value) * -1;}function Percent () {FKeyPad.ReadOut.value = (parseFloat(FKeyPad.ReadOut.value) / 100) * parseFloat(Accumulate);}// End --></SCRIPT><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Text dances in status bar<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat -->

<SCRIPT LANGUAGE="JavaScript">var yourtext = "* YOUR MESSAGE HERE! *";var wedge1=" ";var wedge2=" ";var message1=wedge1+yourtext+wedge2;var dir = "lside";var speed = 50;

function bouncey() {

if (dir == "lside") {message2=message1.substring(2,message1.length)+" ";window.status=message2;setTimeout("bouncey();",speed);message1=message2;

Page 28: Javascript Programs Only

if (message1.substring(0,1) == "*") {dir="rside";

}}

else {message2=" "+message1.substring(0,message1.length-2);window.status=message2;setTimeout("bouncey();",speed);message1=message2;if (message1.substring(message1.length-1,message1.length) == "*") {

dir="lside";}

}}

// -- End Hiding Here --></SCRIPT>

<body onLoad="bouncey()"></body><br><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Visitor and counter<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><script src=http://fastonlineusers.com/online.php?d=www.mohager.co.sr></script><br><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Clock the visitor time visiting the page<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat -->

<HEAD>

<SCRIPT LANGUAGE="JavaScript"><!-- Beginstartday = new Date();clockStart = startday.getTime();function initStopwatch() { var myTime = new Date(); return((myTime.getTime() - clockStart)/1000); }function getSecs() { var tSecs = Math.round(initStopwatch()); var iSecs = tSecs % 60;var iMins = Math.round((tSecs-30)/60);

Page 29: Javascript Programs Only

var sSecs ="" + ((iSecs > 9) ? iSecs : "0" + iSecs);var sMins ="" + ((iMins > 9) ? iMins : "0" + iMins);document.forms[0].timespent.value = sMins+":"+sSecs;window.setTimeout('getSecs()',1000); }// End --></script><BODY onLoad="window.setTimeout('getSecs()',1)"><CENTER><FORM><FONT SIZE="2" FACE="Arial">Time spent here: </FONT><input size=5 name=timespent></FORM></CENTER><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Asking user's name and say welcome<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><SCRIPT LANGUAGE="JavaScript">{var name = prompt ('Your name','');var color = prompt ('Color name','');document.write("<CENTER><FONT FACE=ARIAdL,VERDANA COLOR="+color+" SIZE=5>Welcome To Web Designer "+name+".</FONT><HR NOSHADE WIDTH=450></CENTER><P>")}</SCRIPT><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Clock in website<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><SCRIPT LANGUAGE="JavaScript">var timerID = null;var timerRunning = false;function stopclock (){if(timerRunning)clearTimeout(timerID);timerRunning = false;}function showtime () {var now = new Date();var hours = now.getHours();var minutes = now.getMinutes();var seconds = now.getSeconds()var timeValue = "" + ((hours >12) ? hours -12 :hours)timeValue += ((minutes < 10) ? ":0" : ":") + minutestimeValue += ((seconds < 10) ? ":0" : ":") + secondstimeValue += (hours >= 12) ? " P.M." : " A.M."document.clock.face.value = timeValue;

Page 30: Javascript Programs Only

// you could replace the above with this// and have a clock on the status bar:// window.status = timeValue;

timerID = setTimeout("showtime()",1000);timerRunning = true;}function startclock () {// Make sure the clock is stoppedstopclock();showtime();}</SCRIPT><BODY onLoad="startclock(); timerONE=window.setTimeout"TEXT="ffffff"><CENTER><form name="clock" onSubmit="0"><input type="text" name="face" size=13 value=""></CENTER><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Random background color changer<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><script>// Select fade-effect below:// Set 1 if the background may fade from dark to medium // Set 2 if the background may fade from light to medium // Set 3 if the background may fade from very dark to very light light// Set 4 if the background may fade from light to very light// Set 5 if the background may fade from dark to very dark var fade_effect=3// What type of gradient should be applied Internet Explorer 5x or higher?// Set "none" or "horizontal" or "vertical"var gradient_effect="horizontal"// Speed higher=slowervar speed=60

///////////////////////////////////////////////////////////////////////////// CONFIGURATION ENDS HERE///////////////////////////////////////////////////////////////////////////

var browserinfos=navigator.userAgent var ie4=document.all&&!document.getElementByIdvar ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/)var ns4=document.layersvar ns6=document.getElementById&&!document.allvar opera=browserinfos.match(/Opera/) var browserok=ie4||ie5||ns4||ns6||opera

Page 31: Javascript Programs Only

if (fade_effect==1) {var darkmax=1var lightmax=127

}if (fade_effect==2) {

var darkmax=127var lightmax=254

}if (fade_effect==3) {

var darkmax=1var lightmax=254

}if (fade_effect==4) {

var darkmax=190var lightmax=254

}if (fade_effect==5) {

var darkmax=1var lightmax=80

}var hexc = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F')

var newredvar newgreenvar newbluevar oldredvar oldgreenvar oldblue

var redcol_1var redcol_2 var greencol_1 var greencol_2 var bluecol_1 var bluecol_2 var oldcolorvar newcolorvar firsttime=true var stepred=1var stepgreen=1var stepblue=1

function setrandomcolor() {var range=(lightmax-darkmax)if (firsttime) {

newred=Math.ceil(range*Math.random())+darkmax

Page 32: Javascript Programs Only

newgreen=Math.ceil(range*Math.random())+darkmaxnewblue=Math.ceil(range*Math.random())+darkmaxfirsttime=false

}

oldred=Math.ceil(range*Math.random())+darkmaxoldgreen=Math.ceil(range*Math.random())+darkmaxoldblue=Math.ceil(range*Math.random())+darkmax

stepred=newred-oldredif (oldred>newred) {stepred=1}else if (oldred<newred) {stepred=-1}else {stepred=0}

stepgreen=newgreen-oldgreenif (oldgreen>newgreen) {stepgreen=1}else if (oldgreen<newgreen) {stepgreen=-1}else {stepgreen=0}

stepblue=newblue-oldblueif (oldblue>newblue) {stepblue=1}else if (oldblue<newblue) {stepblue=-1}else {stepblue=0}fadebg()

}function fadebg() {

if (newred==oldred) {stepred=0}if (newgreen==oldgreen) {stepgreen=0}if (newblue==oldblue) {stepblue=0}newred+=steprednewgreen+=stepgreennewblue+=stepblueif (stepred!=0 || stepgreen!=0 || stepblue!=0) {

redcol_1 = hexc[Math.floor(newred/16)]; redcol_2 = hexc[newred%16];

greencol_1 = hexc[Math.floor(newgreen/16)]; greencol_2 = hexc[newgreen%16];

bluecol_1 = hexc[Math.floor(newblue/16)]; bluecol_2 = hexc[newblue%16];

newcolor="#"+redcol_1+redcol_2+greencol_1+greencol_2+bluecol_1+bluecol_2if (ie5 && gradient_effect!="none") {

if (gradient_effect=="horizontal") {gradient_effect=1}if (gradient_effect=="vertical") {gradient_effect=0}

greencol_1 = hexc[Math.floor(newred/16)]; greencol_2 = hexc[newred%16];

bluecol_1 = hexc[Math.floor(newgreen/16)]; bluecol_2 = hexc[newgreen%16];

Page 33: Javascript Programs Only

redcol_1 = hexc[Math.floor(newblue/16)]; redcol_2 = hexc[newblue%16];

var newcolorCompl="#"+redcol_1+redcol_2+greencol_1+greencol_2+bluecol_1+bluecol_2

document.body.style.filter="progid:DXImageTransform.Microsoft.Gradient(startColorstr="+newcolorCompl+", endColorstr="+newcolor+" GradientType="+gradient_effect+")"

}else {

document.bgColor=newcolor }var timer=setTimeout("fadebg()",speed);

} else { clearTimeout(timer)

newred=oldrednewgreen=oldgreennewblue=oldblueoldcolor=newcolorsetrandomcolor()

}}

if (browserok) {window.onload=setrandomcolor

}</script>

<font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Today's Date in website<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><html><head><meta name="GENERATOR" content="Microsoft FrontPage 6.0"><meta name="ProgId" content="FrontPage.Editor.Document"></head><body><center><script LANGUAGE="JavaScript"><!-- Beginmonthnames = new Array("January","Februrary","March","April","May","June","July","August","September","October","November","Decemeber");var linkcount=0;function addlink(month, day, href) {var entry = new Array(3);entry[0] = month; entry[1] = day;entry[2] = href; this[linkcount++] = entry;

Page 34: Javascript Programs Only

}Array.prototype.addlink = addlink;linkdays = new Array();monthdays = new Array(12);monthdays[0]=31; monthdays[1]=28; monthdays[2]=31; monthdays[3]=30; monthdays[4]=31;monthdays[5]=30; monthdays[6]=31; monthdays[7]=31; monthdays[8]=30; monthdays[9]=31;monthdays[10]=30; monthdays[11]=31;todayDate=new Date(); thisday=todayDate.getDay(); thismonth=todayDate.getMonth();thisdate=todayDate.getDate(); thisyear=todayDate.getYear(); thisyear = thisyear % 100;thisyear = ((thisyear < 50) ? (2000 + thisyear) : (1900 + thisyear));if (((thisyear % 4 == 0) && !(thisyear % 100 == 0))||(thisyear % 400 == 0)) monthdays[1]++;startspaces=thisdate;while (startspaces > 7) startspaces-=7;startspaces = thisday - startspaces + 1;if (startspaces < 0) startspaces+=7;document.write("<table border=2 bgcolor=white ");document.write("bordercolor=black><font color=black>");document.write("<tr><td colspan=7><center><strong>" + monthnames[thismonth] + " " + thisyear + "</strong></center></font></td></tr>");document.write("<tr>");document.write("<td align=center>Su</td>"); document.write("<td align=center>M</td>");document.write("<td align=center>Tu</td>"); document.write("<td align=center>W</td>");document.write("<td align=center>Th</td>"); document.write("<td align=center>F</td>");document.write("<td align=center>Sa</td>"); document.write("</tr>"); document.write("<tr>");for (s=0;s<startspaces;s++) {document.write("<td> </td>");}count=1;while (count <= monthdays[thismonth]) {for (b = startspaces;b<7;b++) {linktrue=false;document.write("<td>");for (c=0;c<linkdays.length;c++) {if (linkdays[c] != null) {if ((linkdays[c][0]==thismonth + 1) && (linkdays[c][1]==count)) {document.write("<a href=\"" + linkdays[c][2] + "\">");linktrue=true; } }}if (count==thisdate) {document.write("<font color='FF0000'><strong>");}if (count <= monthdays[thismonth]) {

Page 35: Javascript Programs Only

document.write(count);}else {document.write(" ");}if (count==thisdate) {document.write("</strong></font>");}if (linktrue)document.write("</a>");document.write("</td>");count++;}document.write("</tr>");document.write("<tr>");startspaces=0;}document.write("</table></p>");// End --></script></center></body></html><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Today's Date in website<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat -->

<html><head><meta name="GENERATOR" content="Microsoft FrontPage 6.0"><meta name="ProgId" content="FrontPage.Editor.Document"></head><body><center><script LANGUAGE="JavaScript"><!-- Beginmonthnames = new Array("January","Februrary","March","April","May","June","July","August","September","October","November","Decemeber");var linkcount=0;function addlink(month, day, href) {var entry = new Array(3);entry[0] = month; entry[1] = day; entry[2] = href; this[linkcount++] = entry; }Array.prototype.addlink = addlink;linkdays = new Array();monthdays = new Array(12);monthdays[0]=31;monthdays[1]=28;monthdays[2]=31;monthdays[3]=30;monthdays[4]=31;monthdays[5]=30;monthdays[6]=31;monthdays[7]=31;monthdays[8]=30;monthdays[9]=31;monthdays[10]=30;monthdays[11]=31;todayDate=new Date();

Page 36: Javascript Programs Only

thisday=todayDate.getDay();thismonth=todayDate.getMonth();thisdate=todayDate.getDate();thisyear=todayDate.getYear();thisyear = thisyear % 100;thisyear = ((thisyear < 50) ? (2000 + thisyear) : (1900 + thisyear));if (((thisyear % 4 == 0) && !(thisyear % 100 == 0))||(thisyear % 400 == 0)) monthdays[1]++;startspaces=thisdate;while (startspaces > 7) startspaces-=7;startspaces = thisday - startspaces + 1;if (startspaces < 0) startspaces+=7;document.write("<table border=2 bgcolor=white ");document.write("bordercolor=black><font color=black>");document.write("<tr><td colspan=7><center><strong>" + monthnames[thismonth] + " " + thisyear + "</strong></center></font></td></tr>");document.write("<tr>");document.write("<td align=center>Su</td>"); document.write("<td align=center>M</td>");document.write("<td align=center>Tu</td>"); document.write("<td align=center>W</td>");document.write("<td align=center>Th</td>"); document.write("<td align=center>F</td>");document.write("<td align=center>Sa</td>"); document.write("</tr>");document.write("<tr>");for (s=0;s<startspaces;s++) {document.write("<td> </td>");} count=1;while (count <= monthdays[thismonth]) {for (b = startspaces;b<7;b++) { linktrue=false;document.write("<td>"); for (c=0;c<linkdays.length;c++) {if (linkdays[c] != null) {if ((linkdays[c][0]==thismonth + 1) && (linkdays[c][1]==count)) {document.write("<a href=\"" + linkdays[c][2] + "\">");linktrue=true; } } }if (count==thisdate) { document.write("<font color='FF0000'><strong>"); }if (count <= monthdays[thismonth]) { document.write(count); }else { document.write(" "); } if (count==thisdate) { document.write("</strong></font>");} if (linktrue) document.write("</a>"); document.write("</td>"); count++;} document.write("</tr>"); document.write("<tr>"); startspaces=0;} document.write("</table></p>");// End --> </script></center></body></html><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Save button<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><script>function doSaveAs(){if (document.execCommand){

Page 37: Javascript Programs Only

document.execCommand("SaveAs")}else { alert("Save-feature available only in Internet Exlorer 5.x.") }</script> <form> <input type="button" value="Save This WebPage" onClick="doSaveAs()"

</form><br><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>Two lines following mouse<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><!-- START OF Mouse Cursor Crosshairs DHTML --><!-- SUMMARY BRIEF This DHTML script will make a crosshair to follow your mouse cursor around. You can change the color of the crosshair by changing the color hex codes in the <style> tag in the <head>of your document.--> <!-- Put this portion of the script inside of your <HEAD> tag --><style><!--#leftright, #topdown { position: absolute;left: 0; top: 0; width: 1px; height: 1px; layer-background-color: #FF0000; background-color: #FF0000;z-index: 100; font-size: 1px; }--></style> <!-- Put this code after your <BODY> tag. --><div id="leftright" style="width:expression(document.body.clientWidth-2)"></div><div id="topdown" style="height:expression(document.body.clientHeight-2)"></div><script language="JavaScript1.2"> <!— if (document.all&&!window.print) { leftright.style.width=document.body.clientWidth-2topdown.style.height=document.body.clientHeight-2} else if (document.layers){document.leftright.clip.width=window.innerWidthdocument.leftright.clip.height=1document.topdown.clip.width=1document.topdown.clip.height=window.innerHeight }function followmouse1(){//move cross engine for IE 4+leftright.style.pixelTop=document.body.scrollTop+event.clientY+1topdown.style.pixelTop=document.body.scrollTopif (event.clientX<document.body.clientWidth-2)topdown.style.pixelLeft=document.body.scrollLeft+event.clientX+1elsetopdown.style.pixelLeft=document.body.clientWidth-2}

function followmouse2(e){//move cross engine for NS 4+document.leftright.top=e.y+1document.topdown.top=pageYOffsetdocument.topdown.left=e.x+1}

if (document.all)document.onmousemove=followmouse1else if (document.layers){

Page 38: Javascript Programs Only

window.captureEvents(Event.MOUSEMOVE)window.onmousemove=followmouse2}

function regenerate(){window.location.reload()}function regenerate2(){setTimeout("window.onresize=regenerate",400)}if ((document.all&&!window.print)||document.layers)//if the user is using IE 4 or NS 4, both NOT IE 5+window.onload=regenerate2//--></script><!-- END OF Mouse Cursor Crosshairs DHTML --><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

Date and time following mouse<!-- this script got from www.javascriptfreecode.com-Coded by: Krishna Eydat --><!--END CODE - Powered java script code by <span lang="en-us"><font color="#FFFFFF"><b><font size="5" color="#FFFFFF"><a href="http://www.javakhafan.9f.com.com">http://www.javakhafan.9f.com.com</a></font></b></font></span>--><SCRIPT language=JavaScript> dCol='cc0099';//date colour.fCol='ff99cc';//face colour.sCol='cc99ff';//seconds colour.mCol='008000';//minutes colour.hCol='000080';//hours colour.ClockHeight=40;ClockWidth=40; ClockFromMouseY=0; ClockFromMouseX=100;//Alter nothing below! Alignments will be lost!d=new Array("SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY");m=new Array("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER");date=new Date();day=date.getDate(); year=date.getYear(); if (year < 2000) year=year+1900;TodaysDate=" "+d[date.getDay()]+" "+day+" "+m[date.getMonth()]+" "+year;D=TodaysDate.split('');H='ooo';H=H.split('');

Page 39: Javascript Programs Only

M='oooo'; M=M.split(''); S='.....';S=S.split('');Face='1 2 3 4 5 6 7 8 9 10 11 12';font='tohoma';size=1;speed=0.6; ns=(document.layers); ie=(document.all); Face=Face.split(' ');n=Face.length; a=size*10; ymouse=0; xmouse=0; scrll=0;

props="<font face="+font+" size="+size+" color="+fCol+"><B>";

props2="<font face="+font+" size="+size+" color="+dCol+"><B>";

Split=360/n; Dsplit=360/D.length;

HandHeight=ClockHeight/4.5

HandWidth=ClockWidth/4.5

HandY=-7; HandX=-2.5; scrll=0; step=0.06; currStep=0; y=new Array();x=new Array();Y=new Array();X=new Array();

for (i=0; i < n; i++){y[i]=0;x[i]=0;Y[i]=0;X[i]=0}

Dy=new Array();Dx=new Array();DY=new Array();DX=new Array();

for (i=0; i < D.length; i++){Dy[i]=0;Dx[i]=0;DY[i]=0;DX[i]=0}

if (ns){ for (i=0; i < D.length; i++)

document.write('<layer name="nsDate'+i+'" top=0 left=0 height='+a+' width='+a+'><center>'+props2+D[i]+'</font></center></layer>');

or (i=0; i < n; i++)

document.write('<layer name="nsFace'+i+'" top=0 left=0 height='+a+' width='+a+'><center>'+props+Face[i]+'</font></center></layer>');

for (i=0; i < S.length; i++)

document.write('<layer name=nsSeconds'+i+' top=0 left=0 width=15 height=15><font face=Arial size=3 color='+sCol+'><center><b>'+S[i]+'</b></center></font></layer>');

for (i=0; i < M.length; i++)

document.write('<layer name=nsMinutes'+i+' top=0 left=0 width=15 height=15><font face=Arial size=3 color='+mCol+'><center><b>'+M[i]+'</b></center></font></layer>');

for (i=0; i < H.length; i++)

Page 40: Javascript Programs Only

document.write('<layer name=nsHours'+i+' top=0 left=0 width=15 height=15><font face=Arial size=3 color='+hCol+'><center><b>'+H[i]+'</b></center></font></layer>');}

if (ie){

document.write('<div id="Od" style="position:absolute;top:0px;left:0px"><div style="position:relative">');

for (i=0; i < D.length; i++)

document.write('<div id="ieDate" style="position:absolute;top:0px;left:0;height:'+a+';width:'+a+';text-align:center">'+props2+D[i]+'</B></font></div>');

document.write('</div></div>');

document.write('<div id="Of" style="position:absolute;top:0px;left:0px"><div style="position:relative">');

for (i=0; i < n; i++)

document.write('<div id="ieFace" style="position:absolute;top:0px;left:0;height:'+a+';width:'+a+';text-align:center">'+props+Face[i]+'</B></font></div>');

document.write('</div></div>');

document.write('<div id="Oh" style="position:absolute;top:0px;left:0px"><div style="position:relative">');

for (i=0; i < H.length; i++)

document.write('<div id="ieHours" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:'+hCol+';text-align:center;font-weight:bold">'+H[i]+'</div>');

document.write('</div></div>

document.write('<div id="Om" style="position:absolute;top:0px;left:0px"><div style="position:relative">');

for (i=0; i < M.length; i++)

document.write('<div id="ieMinutes" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:'+mCol+';text-align:center;font-weight:bold">'+M[i]+'</div>');

document.write('</div></div>')

document.write('<div id="Os" style="position:absolute;top:0px;left:0px"><div style="position:relative">');

for (i=0; i < S.length; i++)

Page 41: Javascript Programs Only

document.write('<div id="ieSeconds" style="position:absolute;width:16px;height:16px;font-family:Arial;font-size:16px;color:'+sCol+';text-align:center;font-weight:bold">'+S[i]+'</div>');

document.write('</div></div>')

} (ns)?window.captureEvents(Event.MOUSEMOVE):0;

function Mouse(evnt){

ymouse = (ns)?evnt.pageY+ClockFromMouseY-(window.pageYOffset):event.y+ClockFromMouseY;

xmouse = (ns)?evnt.pageX+ClockFromMouseX:event.x+ClockFromMouseX;

} (ns)?window.onMouseMove=Mouse:document.onmousemove=Mouse;

function ClockAndAssign(){

time = new Date (); secs = time.getSeconds();

sec = -1.57 + Math.PI * secs/30;

mins = time.getMinutes(); min = -1.57 + Math.PI * mins/30;

hr = time.getHours(); hrs = -1.575 + Math.PI * hr/6+Math.PI*parseInt(time.getMinutes())/360;

if (ie){ Od.style.top=window.document.body.scrollTop;

Of.style.top=window.document.body.scrollTop; Oh.style.top=window.document.body.scrollTop;

Om.style.top=window.document.body.scrollTop; Os.style.top=window.document.body.scrollTop;

} for (i=0; i < n; i++){

var F=(ns)?document.layers['nsFace'+i]:ieFace[i].style;

F.top=y[i] + ClockHeight*Math.sin(-1.0471 + i*Split*Math.PI/180)+scrll;

F.left=x[i] + ClockWidth*Math.cos(-1.0471 + i*Split*Math.PI/180);

for (i=0; i < H.length; i++){

var HL=(ns)?document.layers['nsHours'+i]:ieHours[i].style;

HL.top=y[i]+HandY+(i*HandHeight)*Math.sin(hrs)+scrll; HL.left=x[i]+HandX+(i*HandWidth)*Math.cos(hrs); } for (i=0; i < M.length; i++){

var ML=(ns)?document.layers['nsMinutes'+i]:ieMinutes[i].style;

Page 42: Javascript Programs Only

ML.top=y[i]+HandY+(i*HandHeight)*Math.sin(min)+scrll;

ML.left=x[i]+HandX+(i*HandWidth)*Math.cos(min); }

for (i=0; i < S.length; i++){

var SL=(ns)?document.layers['nsSeconds'+i]:ieSeconds[i].style;

SL.top=y[i]+HandY+(i*HandHeight)*Math.sin(sec)+scrll; SL.left=x[i]+HandX+(i*HandWidth)*Math.cos(sec);

}for (i=0; i < D.length; i++){

var DL=(ns)?document.layers['nsDate'+i]:ieDate[i].style;

DL.top=Dy[i] + ClockHeight*1.5*Math.sin(currStep+i*Dsplit*Math.PI/180)+scrll;

DL.left=Dx[i] + ClockWidth*1.5*Math.cos(currStep+i*Dsplit*Math.PI/180); }

currStep-=step;}

function Delay(){

scrll=(ns)?window.pageYOffset:0;

Dy[0]=Math.round(DY[0]+=((ymouse)-DY[0])*speed);

Dx[0]=Math.round(DX[0]+=((xmouse)-DX[0])*speed);

for (i=1; i < D.length; i++){ Dy[i]=Math.round(DY[i]+=(Dy[i-1]-DY[i])*speed);

Dx[i]=Math.round(DX[i]+=(Dx[i-1]-DX[i])*speed);}y[0]=Math.round(Y[0]+=((ymouse)-Y[0])*speed); x[0]=Math.round(X[0]+=((xmouse)-X[0])*speed); for (i=1; i < n; i++){ y[i]=Math.round(Y[i]+=(y[i-1]-Y[i])*speed); x[i]=Math.round(X[i]+=(x[i-1]-X[i])*speed); }

ClockAndAssign(); setTimeout('Delay()',20); } if (ns||ie)window.onload=Delay; </SCRIPT><font face="Tahoma"><a target="_blank" href="http://www.javascriptfreecode.com/"><span style="font-size: 8pt; text-decoration: none">JavaScript Free Code</span></a></font>

CREATING A COOKIE

<html><head><script type="text/javascript">function getCookie(c_name){var i,x,y,ARRcookies=document.cookie.split(";");for (i=0;i<ARRcookies.length;i++)

Page 43: Javascript Programs Only

{ x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } }}

function setCookie(c_name,value,exdays){var exdate=new Date();exdate.setDate(exdate.getDate() + exdays);var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());document.cookie=c_name + "=" + c_value;}

function checkCookie(){var username=getCookie("username");if (username!=null && username!="") { alert("Welcome again " + username); }else { username=prompt("Please enter your name:","");

if (username!=null && username!="") { setCookie("username",username,365); } } }</script></head><body onload="checkCookie()"></body></html>SIMPLE TIMING<html> <head> <script type="text/javascript">function timeMsg(){ var t=setTimeout("alertMsg()",3000); }function alertMsg(){alert("Hello");}</script></head><body><form><input type="button" value="Display alert box in 3 seconds" onClick="timeMsg()" /></form></body></html>

ANOTHER SIMPLE TIMING

<html><head><script type="text/javascript">function timedText(){

Page 44: Javascript Programs Only

var t1=setTimeout("document.getElementById('txt').value='2 seconds!'",2000);var t2=setTimeout("document.getElementById('txt').value='4 seconds!'",4000);var t3=setTimeout("document.getElementById('txt').value='6 seconds!'",6000);}</script></head><body><form><input type="button" value="Display timed text!" onclick="timedText()" /><input type="text" id="txt" /></form><p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p> </body></html>

Timing event in an infinite loop<html><head><script type="text/javascript">var c=0;var t;var timer_is_on=0;

function timedCount(){document.getElementById('txt').value=c;c=c+1;t=setTimeout("timedCount()",1000);}

function doTimer(){if (!timer_is_on) { timer_is_on=1; timedCount(); }}</script> </head>

<body><form><input type="button" value="Start count!" onClick="doTimer()"><input type="text" id="txt"></form><p>Click on the button above. The input field will count forever, starting at 0.</p></body></html>A clock created with a timing event<html><head><script type="text/javascript">

Page 45: Javascript Programs Only

function startTime(){var today=new Date();var h=today.getHours();var m=today.getMinutes();var s=today.getSeconds();// add a zero in front of numbers<10m=checkTime(m);s=checkTime(s);document.getElementById('txt').innerHTML=h+":"+m+":"+s;t=setTimeout('startTime()',500);}

function checkTime(i){if (i<10) { i="0" + i; }return i;}</script></head>

<body onload="startTime()"><div id="txt"></div></body></html>

Create a direct instance of an object<html><body>

<script type="text/javascript">personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}

document.write(personObj.firstname + " is " + personObj.age + " years old.");</script>

</body></html>Create an object constructor<html><body>

<script type="text/javascript">function person(firstname,lastname,age,eyecolor){this.firstname=firstname;this.lastname=lastname;this.age=age;this.eyecolor=eyecolor;

Page 46: Javascript Programs Only

}

myFather=new person("John","Doe",50,"blue");

document.write(myFather.firstname + " is " + myFather.age + " years old.");</script>

</body></html>

JavaScript Error Handling

The try...catch statement

<html><head><script type="text/javascript">

var txt="";

function message()

{ try {

adddlert("Welcome guest!");

}catch(err)

{

txt="There was an error on this page.\n\n";

txt+="Error description: " + err.description + "\n\n";

txt+="Click OK to continue.\n\n";

alert(txt);

}

}

</script></head><body>

<input type="button" value="View message" onclick="message()" />

</body> </html>

The try...catch statement with a confirm box

Page 47: Javascript Programs Only

<html><head><script type="text/javascript">

var txt="";

function message()

{ try

{

adddlert("Welcome guest!");

}

catch(err)

{

txt="There was an error on this page.\n\n";

txt+="Click OK to continue viewing this page,\n";

txt+="or Cancel to return to the home page.\n\n";

if(!confirm(txt))

{ document.location.href="http://www.w3schools.com/";

}

}

}

</script></head><body>

<input type="button" value="View message" onclick="message()" />

</body></html>

The onerror event

<html>

<head>

<script type="text/javascript">

onerror=handleErr; var txt="";

function handleErr(msg,url,l)

{ txt="There was an error on this page.\n\n";

Page 48: Javascript Programs Only

txt+="Error: " + msg + "\n";

txt+="URL: " + url + "\n"; txt+="Line: " + l + "\n\n"; txt+="Click OK to continue.\n\n";

alert(txt); return true;

} function message()

{ adddlert("Welcome guest!");

}

</script></head><body>

<input type="button" value="View message" onclick="message()" />

</body></html>