Thursday, April 14, 2011

YouTube - Microsoft MIX - Internet Explorer 10 Demonstration

http://www.youtube.com/watch?v=3870_toHLjo&feature=

Tuesday, April 12, 2011

Basic JavaScripting


Java Script Basic:

1)    INTRODUCTION

http://www.echoecho.com/p.gifJavascript is a scripting language that will allow you to add real programming to your webpages. You can create small application type processes with javascript, like a calculator or a primitive game of some sort. However, there are more serious uses for javascript:
  • Browser Detection
    Detecting the browser used by a visitor at your page. Depending on the browser, another page specifically designed for that browser can then be loaded.
  • Cookies
    Storing information on the visitor's computer, then retrieving this information automatically next time the user visits your page. This technique is called "cookies".
  • Control Browsers
    Opening pages in customized windows, where you specify if the browser's buttons, menu line, status line or whatever should be present.
  • Validate Forms
    Validating inputs to fields before submitting a form.
    An example would be validating the entered email address to see if it has an @ in it, since if not, it's not a valid address.
Before you start out with more complex javascripts you should understand the basics.
This tutorial covers all the core things you need to know before you can build and customize your own cool scripts.

2)    WHERE TO PLACE IT

Since javascript isn't HTML, you will need to let the browser know in advance when you enter javascript to an HTML page. This is done using the <script> tag. The browser will use the <script> type="text/javascript"> and </script> to tell where javascript starts and ends.
Consider this example:
<html>
<head>
<title>My Javascript Page</title>
</head>

<body>
<script type="text/javascript">
alert("Welcome to my world!!!");
</script>

</body>
</html> 

The word 
alert is a standard javascript command that will cause an alert box to pop up on the screen. The visitor will need to click the "OK" button in the alert box to proceed. By entering the alert command between the <script type="text/javascript"> and </script> tags, the browser will recognize it as a javascript command. If we had not entered the <script> tags, the browser would simply recognize it as pure text, and just write it on the screen. You can enter javascript in both the <head> and <body> sections of the document. In general however, it is advisable to keep as much as possible in the <head>section.

3)    THE FIRST SCRIPT:

Knowing that javascript needs to be entered between <script> tags, is a start. But there are a few other things you need to know before writing your first javascript:
  • Javascript lines end with a semicolon. You may have noticed from the example on the previous page that javascript lines end with a semicolon. You can easily put all your javascript on a single line without destroying the performance of it. However, you would destroy the overview of your script so it is not advisable.
  • Always put the text within " ". When entering text to be handled by javascript, you should always put the text within " ". If you forget to enclose your text in " ", javascript will interpret your text as being variables rather than text. In the next section you will learn why this would cause an error to your script.
  • Capital letters are different from lowercase letters. You should always remember that capital letters are different from lowercase letters. This means that when you write commands in javascript, you need to type capital letters in the correct places, and nowhere else.
Incorrect capitalization is probably the most common source of error for javascript programmers on all levels!! Now consider this example:
Instead of having javascript write something in a popup box we could have it write directly into the document. 
<html>
<head>
<title>My Javascript Page</title>
</head>

<body>
<script>
document.write("Welcome to my world!!!");
</script>

</body>
</html> 

The 
document.write is a javascript command telling the browser that what follows within the parentheses is to be written into the document.
Note: When entering text in javascript you need to include it in " ".
The script in the example would produce this output on your page:
Welcome to my world!!!
Consider this example to learn where javascript writes the text:
<html>
<head>
<title>My Javascript Page</title>
</head>
<body>
Hello!!!<br>
<script>
document.write("Welcome to my world!!!<br>");
</script>

Enjoy your stay...<br>
</body>
</html> 
The output from this example would look like this:
Hello!!!
Welcome to my world!!!
Enjoy your stay...
As you can see, javascript simply writes the text to where the script is placed within the HTML codes. An interesting aspect is that you can write all kinds of HTML tags to webpages with the document.write method. For instance, if you wanted to make a long table that compared Fahrenheit and Celsius, instead of actually typing all the values into the table, you could have javascript calculate the values and write the table to the document. An example of a javascript generated table can be seen on the page explaining the hexadecimal colorsytem. On that page, there are 15 tables with 25 columns in each. Each cell shows different mixtures of the basic colors red, green and blue. To set up these tables in HTML would demand almost an entire days work. Using javascript for the same purpose took less than 15 minutes!

4)    CAPITAL LETTERS:

It is extremely important to be aware that javascript makes a sharp distinction between capital and lowercase letters. Javascript does not consider a variable named myvalue to be the same as a variable named MYVALUE. Consider these examples:
Example 1
Example 2 
<html>
<head>
<title>My Page</title>
</head>
<body>
<script>
myvalue=2;
myvalue=5;
result=myvalue+myvalue;

document.write(result);
</script>
</body>
</html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<script>
myvalue=2;
MyValue=5;
result=myvalue+MyValue;

document.write(result);
</script>
</body>
</html> 
The output of example 1 would be 10 (5+5).The output of example 2 would be 7 (2+5).
The best advice is to use the same syntax on all variables. Either writes all variables in small letters, start with one capital letter or write all variables in capitals. Which syntax you chose is not important as long as you chose just one!

5)    POP UP BOXES:

It is possible to make three different kinds of popup windows. Try clicking the buttons below to see the differences:


ALERT BOX:
The syntax for an alert box is: 
alert("yourtext"); The user will need to click "OK" to proceed.
Typical use is when you want to make sure information comes through to the user. Examples could be warnings of any kind. (Typical examples are "Adult Content", or technical matters like "This site requires Shockwave Flash plug-in").
CONFIRM BOX:
The syntax for a confirm box is: 
confirm("yourtext"); The user needs to click either "OK" or "Cancel" to proceed. Typical use is when you want the user to verify or accept something. Examples could be age verification like "Confirm that you are at least 57 years old" or technical matters like "Do you have a plug-in for Shockwave Flash?"
- If the user clicks "OK", the box returns the value 
true.
- If the user clicks "Cancel", the box returns the value 
false.
if (confirm("Do you agree")) {alert("You agree")}
else{alert ("
You do not agree")};
Note: The if statement is explained later in this tutorial.
PROMPT BOX:
The prompt box syntax is: 
prompt("yourtext","defaultvalue"); The user must click either "OK" or "Cancel" to proceed after entering the text.Typical use is when the user should input a value before entering the page. Examples could be entering user's name to be stored in a cookie or entering a password or code of some kind.
- If the user clicks "OK" the prompt box returns the entry.
- If the user clicks "Cancel" the prompt box returns 
null.
Since you usually want to use the input from the prompt box for some purpose it is normal to store the input in a variable, as shown in this example:
username=prompt("Please enter your name","Enter your name here"); 

 

6)    VARIABLES:

Variables can be compared to small boxes with names. If you were to store 5 pair of shoes, you might have a box for each pair. On each box you would write what is in it. The boxes would be your variables. Places to store things.
  • The name on the boxes would be the variable names. The ones you'd use when referring to each of the boxes.
  • And finally the shoes, would be the content of the variables. What is stored in the boxes.

A variable is simply a place in the computer's memory to store information. All variables are referred to by the unique name you assigned to them. Consider this example:
<html>
<head>
<title>My Javascript Page</title>
</head>

<body>
<script>
myname="Henrik";
document.write(myname);

</script>
</body>
</html> 
This example would write "Henrik" in the document.
Note that when you want text to be stored in a variable you need to put the text in " ".
The reason is that javascript uses " " to tell the difference between text and variables.
Look at this example to see the importance of this.
<html>
<head>
<title>My Javascript Page</title>
</head>

<body>
<script>
Henrik="my first name";
myname=Henrik;
document.write(myname);

</script>
</body>
</html> 

Try to predict the output of the example before reading on.
·         In the first line, the text "my first name" is stored in the Henrik variable. 
·         In the second line, the Henrik variable is stored in the myname variable.
·         Finally in line 3, the myname variable is written to the document.

The result is that "my first name" will be written on the page.
ASSIGNING VALUES TO VARIABLES
The most common way to assign a value to a variable is using the equals sign. Consider these examples to see the different ways variables can be assigned to contain either values or text.
Note in particular how parentheses can be used to control how complex formulas are handled.
Example
Resulting value 
a=2;
a=2; a++;
a=2; a--;
a=2; b=3; c=a+b;
a=2; d=a+6;
First="Henrik";
Last="Petersen";
Full=First+" "+Last;
a=2*7;
b=20/5;
c=(20/5)*2;
d=20/(5*2);
a=2
a=3    (2+1)
a=1    (2-1)
c=5    (2+3)
d=8    (2+6)
First=Henrik
Last=Petersen
Full=Henrik Petersen
a=14  (2*7)
b=4    (20/5)
c=8    (4*2)
d=2    (20/10) 

ARITHMETHIC OPERATORS
The above table includes the so-called "arithmethic operators" 
a++ and a--. You could really live well without these, since what they do can be achieved by using the other operators available.
However you will often see them used in scripts, and you might even be lazy enough to use them yourself, since it is faster to type 
a++; than it is to typea=a+1;.

Operator
Explanation
Example 
++
increment
a=5;
a++;

a would now equal 6 
--
decrement
a=5;
a--;

a would now equal 4 
%
returns modulus,
which is what is left when
two numbers are divided.
a=8 % 3;
a would now equal 2,
since 8 can be divided
by 3 two times leaving
a remainder of 2.

COMPARING VARIABLES
There are several different ways to compare variables.The simplest is comparing for equality, which is done using a double equals sign:
 
if (a==b) {alert("a equals b")};
if (lastname=="Petersen") {alert("Nice name!!!")};
Note: The 
if statement is explained in the next section.
If you forget to use double equals signs when comparing variables for equality, and use a single equals sign instead, you will not compare the variables. What will happen is that the variable on the left side of the equals sign will be assigned the value of the variable to the right.
An example of the error:

if (lastname="Petersen") {alert("Nice name!!!")};
This is a very common bug that will totally ruin the script. This table contains the different comparing operators: 
Operator
Explanation
Example 
==
equal to
4==5 (false)
5==5 (true)
5==4 (false) 
!=
not equal to
4!=5 (true)
5!=5 (false)
5!=4 (true)
< 
less than
4<5 (true)
5<5 (false)
5<4 (false) 
> 
greater than
4>5 (false)
5>5 (false)
5>4 (true) 
<=
less than or equal to
4<=5 (true)
5<=5 (true)
5<=4 (false) 
>=
greater than or equal to
4>=5 (false)
5>=5 (true)
5>=4 (true) 
On the function page you will learn more about global and local variables.
On the 
array page you will learn more about ways to work with large amounts of variables.

7)    IF AND ELSE:

Sometimes javascript requires the ability to make distinctions between different possibilities.
For example, you might have a script that checks which browser the user arrives with. If it's MSIE, a page specifically designed for that browser should be loaded, if it's Netscape another page should be loaded. The general syntax for if statements is:

if (condition) {action1} else {action2};

An example could be:
if (browser=="MSIE") {alert("You are using MSIE")}
else {
alert("You are using Netscape")}; 
Again it is important to note that if is written as "if". Using the capital "IF" would cause an error.
Also note that when comparing variables you will need to have two equals signs next to each other (==). If we wrote 
browser="MSIE" we would actually store "MSIE" in the variable called browser. When you write browser=="MSIE" javascript knows that you want it to compare rather than assign a value. The next section explains the different operators (=<> etc.). More complex if statements can be made by simply entering new if statements in the else part:

if (condition) {action1}
else {if (
condition) {action2} else {action3};};

An example:
if (browser=="MSIE") {alert("You are using MSIE")}
else {if (
browser=="Netscape") {alert("You are using Netscape")}
else {
alert("You are using an unknown browser")};};

AND, OR & NOT

To further enhance your if statements you can use the so-called logical operators. And is written as 
&& and is used when you want to check if more than one condition is true.

Ex: If the basket contains egg 
and the basket contains bacon, we can have egg and bacon.

The syntax is: 
if (condition && condition) {action}
if (hour==12 && minute==0) {alert("it's noon")}; 

Or is written as 
|| and is used when more than a one condition should result in the check being true. (|| is achieved by using the shift key combined with the \ key)

Ex: If the basket contains milk 
or the basket contains water, we can have something to drink.

The syntax is: 
if (condition || condition) {action}
if (hour==11 || hour==10) {alert("it's less than 2 hours till noon")}; 

Not is written as 
! and is used to invert the result.

Ex: If 
not the basket contains egg or not the basket contains bacon, we cant have egg and bacon.

The syntax is: 
if (!(condition)) {action}
if (!(hour==11)) {alert("it's more than 1 hour till noon")}; 

8)    FUNCTIONS:

Instead of just adding your javascript to the page and having the browser perform the tasks as soon as the script is read, you might want your javascript to be performed only upon the detection of a certain event.

For example, if you made a javascript code that changed the background color of the page when the user clicked a button, then you would need to tell the browser, that the script should not be performed right away when loaded.

To keep the browser from performing a script as soon as it is loaded you need to write the script as a function.

Javascript written into functions will not be performed until you specifically ask for it. This way you gain complete control of the timing.

Look at this example of script lines written as a function:
<html>
<head>
<script>
function myfunction()
{
alert("Welcome to my world!!");
}

</script>
</head>

<body>
<form name="myform">
<input type="button" value="Hit me" 
onclick="myfunction()">
</form>
</body>
</html> 

Click the button to see what the script in the example does:
Top of Form
Bottom of Form

If the line: 
alert("Welcome to my world!!"); had not been written within a function, it would simply be performed as soon as the line was loaded. But since we wrote it as a function, it was not performed until you hit the button.The call of the function is in this line: 
<input type="button" value="Click Here" onclick="myfunction()">

As you can see, we placed the button in a form and added the event
onClick="myfunction()" to the properties of the button. The next page gives a detailed description of the different events you could use to trigger functions. The general syntax for a function is:

function functionname(variable1, variable2,..., variableX)

// Here goes the javascript lines for the function
}
The { and the } marks the start and end of the function. A typical bug when entering javascript functions is to forget about the importance of capitals in javascript. The word function must be spelled exactly as function.Function or FUNCTION would cause an error. Furthermore, use of capitals matters in the name of the function as well. If you had a function called myfunction() it would cause an error if you referred to it asMyfunction()MYFUNCTION() or MyFunction().

9)    EVENTS:

Events are actions that can be detected by javascript. An example would be the onmouseover event, which is detected when the user moves the mouse over an object. Another event is the onload event, which is detected as soon as the page is finished loading. Usually, events are used in combination with functions, so that the function does not start until the event happens. An example would be a function that would animate a button. The function simply shifts two images. One image that shows the button in an "up" position, and another image that shows the button in a "down" position. If this function is called using an onmouseover event, it will make it look as if the button is pressed down when the mouse is moved over the image.The following are the most important events recognized by javascript:
Event
Detected when
HTML tags 
onfocus=""
Form field gets focus
select, text, textarea 
onblur=""
Form field looses focus
select, text, textarea 
onchange=""
Content of a field changes
select, text, textarea 
onselect=""
Text is selected
text, textarea 
onmouseover=""
Mouse moves over a link
onmouseout=""
Mouse moves out of a link
onclick=""
Mouse clicks an object
A, button, checkbox,
radio, reset, submit 
onload=""
Page is finished loading
body, frameset 
onunload=""
Browser opens new document
body, frameset 
onSubmit=""
Submit button is clicked
form 

Events are used for two main purposes: 
·         To perform a function upon detection of the event,
·         To show a popup box upon detection of the event.
Below is a brief description of the main purposes for each event. onFocus, onblur and onchange are mainly used in combination with validation of form fields. Lets say you had a function called validateEmail() that would check to see if an entered email address has an @ in it, and if it has a meaningful end, such as "com", "net" or whatever. Furthermore, suppose the user could enter his email address in a form. You would then use the onchange event to call the function whenever the user changes the content of the field:
<input type="text" size="20" onchange="validateEmail()">; 

Click 
here to learn more about forms.
Click 
here to learn more about form field validation.

onload and onunload are mainly used for popups that appear when the user enters or leaves the page. Another important use is in combination with cookies that should be set upon arrival or leaving your pages. For example, you might have a popup asking the user to enter his name upon his first arrival to your page. The name is then stored in a cookie. Furthermore, when the visitor leaves your page a cookie stores the current date. Next time the visitor arrives at your page, it will have another popup saying something like: "Welcome Bill Clinton, this page has not been updated since your last visit 8 days ago".

Click 
here to learn more about setting cookies.
Click 
here to learn more about popup boxes.

Another common use of the 
onLoad and onunload events is: Some annoying pages have a function that immediately opens several other windows as soon as you enter the page. This is a clear break of netiquette, and is not considered proper webdesign. onsubmit is used for one major purpose: To validate all fields within a form before actually submitting it. In the above example for onchange we showed how you can validate a single form field. Sometimes however, the visitor might find it annoying to have validations in the middle of entering fields on a form. Rather than validating after each input, you might want the form to be validated only upon clicking the submit button. This can be done using the onsubmit event. Assume you made a function named checkform() that would validate entries to a form. Now you want this function to be called when the user clicks the submit button. If the content is not accepted by your function the submit should be cancelled. This way nothing would be submitted unless your function accepted the content. What you should do, is: add an onsubmit event to the <form> tag this way:
<form method="yourchoice" action="yourchoice" onsubmit="return checkform()"

The function 
checkform() returns either true or false.
If it returns 
true the submit will take place.
If it returns 
false the submit will be cancelled.

Click 
here to learn more about forms.
Click 
here to learn more about form validation.

onmouseover and onmouseout are mainly used for one purpose: To create animated buttons.
You may have noticed that these events can only be used in combination with the link tag <a>.
However, the events are often more useful in combination with the image tag<img>. The trick to making the event work on an image is simply to turn the image into a link. (If the image is not supposed to actually work as a link, you could always make it link to an empty anchor, as shown in the example below). Example: an alert box appears when an onmouseover is detected on an image:
http://www.echoecho.com/rainbow.gif
The HTML from the example:

<a href="#" onmouseover="alert('I detected an onmouseover event'); return false" onmouseout="alert('I detected an onmouseout event'); return false">
<img src="rainbow.gif" width="60" height="60">
</a> 

Note: The href="#" links the image to nowhere. If you really wanted the image to link to a page you should enter the address of the page here instead.

Click 
here to learn more about links and anchors.
Click 
here to learn more about alert boxes.

10)  LOOPS:

Imagine that you wanted a script to perform the same routine over and over again 50 times in a row. An example could be if you wanted a script to produce a table comparing temperatures in Fahrenheit and Celsius. The script should produce 50 lines in a table showing different temperatures according to the two scales. Instead of adding 50 almost equal lines in your script you could use loops to make the script perform a task like this. There are two different kinds of loops: for and while. The for loop is used when you know in advance how many times the script should perform. For example if you wanted it to create exactly 50 lines. The while loop is used when you want the loop to continue until a certain condition becomes true. For example, if you wanted to make a table comparing Celsius and Fahrenheit, stepping 15 degrees for each row, and you wanted the table to contain values up to 1200 degrees of Celsius. Below is a description of each of these two loops:

FOR LOOPS:

SYNTAX:
for (variable=startvalue; variable<=endvalue;variable=variable+incrementfactor)
{

// Here goes the script lines you want to loop.
}


Enter a 
variablename where it says variable.
Enter the 
startvalue of the loop where it says startvalue.
Enter the 
endvalue of the loop where it says endvalue.
Enter the 
factor each loop should increment where it says incrementfactor.

Note: The incrementfactor could be negative if you wanted.
Furthermore the 
<= could be any comparing statement, ex. >== or whatever.

EXAMPLE: 
<html>
<head>
<title>Celsius-Fahrenheit Converter</title>
</head>

<body>
<table border=3>
<tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr>
<script language="javascript">
for (celsius=0; celsius<=50; celsius=celsius+1)
{
document.write("<tr><td>"+celsius+"</td><td>"
+((celsius*9/5)+32)+"</td></tr>");
}

</script>
</table>
</body>
</html> 


Click 
here to see the page from this example.

WHILE LOOPS:

SYNTAX: 
while (variable<=endvalue)
{

// Here goes the script lines you want to loop.
} 


Enter a 
variablename where it says variable.
Enter the 
endvalue of the loop where it says endvalue.

Note: The 
<= could be anything that would fit the purpose ex. >== or whatever. 

EXAMPLE: 
<html>
<head>
<title>Celsius-Fahrenheit converter</title>
</head>

<body>
<table border=3>
<tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr>
<script language="javascript">
celsius=0;
while (celsius<=50)
{
document.write("<tr><td>"+celsius+
"</td><td>"+((celsius*9/5)+32)+"</td></tr>");
celsius=celsius+1;
}

</script>
</table>
</body>
</html>


Click 
here to see the page from this example.
BREAK & CONTINUE

Two special commands can be used in loops: 
break and continue. break simply breaks the loop and continues with what might follow after the loop. An example would be if you had a loop calculate the squareroot of numbers decrementing from 50. Since calculating the square root of a negative number is an illegal mathemathic operation you would like the loop to end when the square root of zero had been calculated. To do this you would add this inside your loop:

if (value==0) {break};

continue breaks the current loop and continues with the next value. An example would be if you had a loop that divided a certain value with a factor of numbers ranging from -50 to +50. Since division by zero is an illegal mathemathic procedure the loop would look like this:

for (value=-50; value<=50; value=value+1)
{
if (value==0) {
continue};
document.write((100/value)+"<br>");

 

11)  ARRAYS:

When working with more complex scripts you might face a situation in which you would have many more or less similar variables. Instead of being forced to write a line for each operation
done to such a variable, you can use arrays to help you automate the process.Consider this example:
Example 1
Example 2 
value1=10;
value2=20;
value3=30;
....
here would go 96 similar lines
....
value100=1000
value=new Array;
for (number=1; number<=100; number=number+1)
value[number]=number*10}; 


In example 1 you would need to enter 100 lines to perform an operation on your variables. In example 2 you only need to enter 3 lines no matter how many variables you have. An array must be defined before referring to any of the variables in it. This is done using the syntax: variablename=
new Array; Replace variblename with the desired name of your array.
Note: new must be written in small letters and Array must start with a capital A.
As the example indicated, arrays become extremely powerful when used in combination with loops. However, you don't have to handle array variables in loops.  Single variables can be addressed with a syntax like this:

value[9]=170;

Advanced Scripts:

1)    BROWSER DETECTION:

For various reasons, it may be useful to detect the visitor's browser type and version. For instance, you may want to have an advanced page for users arriving with version 4 browsers, and a simple page for users arriving with older browsers. Maybe you want to make a page that sends Netscape to one page and MSIE to another page. In any case, you will need to have visitors arrive at one page, on which the browser detection takes place. The page will then automatically load the page the user should be presented with. Javascript is an ideal tool for this purpose.
Technique:
Browser detection is based on the navigator object. This object holds name, version, etc. of the browser. Therefore it is pretty simple to write a script that will read these variables and return the name and version of the current browser. All you really need to do is use the indexOf function to find the version number. This tutorial will teach you how.
THE CODE:
First create a page with the standard skeleton code for all webpages:

BROWSER DETECTION SCRIPT - Step 1/3

<html>
<head>
<title>Browserdetection</Title>
</head>

<body>
</body>
</html>


The javascript that will detect the browser makes use of the 
navigator object. This object holds these interesting variables:

VARIABLES
DESCRIPTION
navigator.appCodeName 
The code name of the browser
(e.g. Mozilla) 
navigator.appName
The name of the browser
(e.g. Netscape or Microsoft Internet Explorer) 
navigator.appVersion
The browser version (e.g. 3.0 or 4.0) 
navigator.userAgent
The header information for the browser.
(e.g. Mozilla/4.0) 
navigator.platform
The users operating system
(e.g. WIN32)


In short, all we need to do is have the webpage run our script once it's loaded. This is done by simply writing the javascript code without function declarations. The following lines should be added to the <head> section of the document:

BROWSER DETECTION SCRIPT - Step 2/3

<html>
<head>
<title>Browser detection</Title>
<Script Language="JavaScript">
browsername=navigator.appName;
if (browsername.indexOf("Netscape")!=-1) {browsername="NS"}
else
{if (browsername.indexOf("Microsoft")!=-1) {browsername="MSIE"}
else {browsername="N/A"}};
</script>

</head>

<body>
</body>
</html>
The above lines store the name of the browser in the variable called browsername. If the browser is Microsoft Internet Explorer, "MSIE" is stored in the variable. If it is a Netscape browser, "NS" is stored in the variable. If it's none of the above, "N/A" is stored in the variable.

Note - The use of indexOf() in the above script:

In the above script you can see this line:

if (browsername.indexOf("Microsoft")!=-1) {browsername="MSIE"}

The function 
browsername.indexOf("Microsoft") checks the variablebrowsername for the first appearance of the word Microsoft.

If 
Microsoft is not present, the result will be -1.

So if 
browsername.indexOf("Microsoft") does not equal -1 ( != -1 ) it means that the word Microsoft is present somewhere in the browsername variable - and thus, the current browser is Microsoft Internet Explorer.

Now we need to find the version of the relevant browser. Since navigator.appVersion does not simply hold a value, like 2, 3 or 4, but rather would hold a text, like "3.0b4Gold (Win95; I)", we need to make a little check of the text before we can save a more convenient value in the variable called browserversion. 

browserversion="0";
if (navigator.appVersion.indexOf("2.")!=-1) {browserversion="2"};
if (navigator.appVersion.indexOf("3.")!=-1) {browserversion="3"};
if (navigator.appVersion.indexOf("4.")!=-1) {browserversion="4"};
if (navigator.appVersion.indexOf("5.")!=-1) {browserversion="5"};
if (navigator.appVersion.indexOf("6.")!=-1) {browserversion="6"};


First we assign the value zero to the variable. If none of the checks results in assigning a value to the variable, it will still hold the zero value after the checks. A value of zero thus means that the browserversion was not available. The next 3 lines look for version numbers 2., 3., 4. and 5.
If navigator.appVersion contains any of the numbers, the value is stored in the variable called "browserversion". The complete script now looks like this:

BROWSER DETECTION SCRIPT - Step 3/3

<html>
<head>
<title>Browser detection</Title>
<Script Language="JavaScript">
browsername=navigator.appName;
if (browsername.indexOf("Netscape")!=-1) {browsername="NS"}
else
{if (browsername.indexOf("Microsoft")!=-1) {browsername="MSIE"}
else {browsername="N/A"}};
browserversion="0";
if (navigator.appVersion.indexOf("2.")!=-1) {browserversion="2"};
if (navigator.appVersion.indexOf("3.")!=-1) {browserversion="3"};
if (navigator.appVersion.indexOf("4.")!=-1) {browserversion="4"};
if (navigator.appVersion.indexOf("5.")!=-1) {browserversion="5"};
if (navigator.appVersion.indexOf("6.")!=-1) {browserversion="6"}; 

</script>
</head>

<body>
</body>
</html>

Now the script holds two variables: browsername and browserversion. This information can be used for whatever purpose we choose. The browser detection itself does nothing. All it does is - detect the visitors browser. We still haven't added 
if-statements that tells the browser what it should do in the different cases. In the example on the next page you will see how you can add if-statements to the browser detection script - in order to send visitors to relevant pages.
EXAMPLE:
In this example we send Netscape visitors to Yahoo, while we send MSIE visitors to either Hotbot or MSN depending on the browser version. If it's none of the above the visitor is sent to Webcrawler.

BROWSER DETECTION SCRIPT
- with if statements

<html>
<head>
<title>Browser detection</Title>
<Script Language="JavaScript">
// Browserdetectionscript made by Henrik Petersen / NetKontoret
// Script explained at www.echoecho.com/javascript.htm
// Please do not remove this and the two lines above.
// Detect the browsername
browsername=navigator.appName;
if (browsername.indexOf("Netscape")!=-1) {browsername="NS"}
else
{if (browsername.indexOf("Microsoft")!=-1) {browsername="MSIE"}
else {browsername="N/A"}};

//detect the browserversion
browserversion="0";
if (navigator.appVersion.indexOf("2.")!=-1) {browserversion="2"};
if (navigator.appVersion.indexOf("3.")!=-1) {browserversion="3"};
if (navigator.appVersion.indexOf("4.")!=-1) {browserversion="4"};
if (navigator.appVersion.indexOf("5.")!=-1) {browserversion="5"};
if (navigator.appVersion.indexOf("6.")!=-1) {browserversion="6"};

// Send visitor to relevant pages
if (browsername=="NS") {window.location="http://www.yahoo.com"};
if (browsername=="MSIE"){
  if (browserversion<4){window.location="http://www.hotbot.com"}
  else {window.location="http://www.msn.com"}
}
if (browsername=="N/A") {window.location="http://www.webcrawler.com"};

</script>
</head>

<body>
</body>
</html>


Copy the code from this example to create your own browser detection page. Customize it by adding your own 
if statements and URLs at the bottom of the script.

2) ANIMATED BUTTONS:

THE TECHNIQUE:

We place the button on the page as we would have placed any other image on a webpage. 
Then we add an 
onMouseOver event to the image. The event causes the browser to run a javascript function that will replace the initial image with another image. Finally we add an onMouseOut event to the image as well. This event causes the browser to run a javascript function that inserts the initial image again when the user moves the mouse away from the image. The technique is thus a two step process: First, you need to add mouse event settings to the HTML tags of the images. Second, you need to add a script that will be performed when the browser detects the mouse events. 

THE CODE:

Before you can add an animated button to your page you need to add the button image itself.
After adding the button image to the webpage you need to add a few comments to the image tag.
After that you can add the javascript that changes the image when the mouse moves over it. The first half of this page covers the plain HTML code for inserting an image so that javascript can refer to it. The second half covers the javascript that changes the image when a mouseover occurs.

THE HTML CODE

A regular image that works as a link button looks somewhat like this in HTML code:
<a href="mypage.htm">
<Img Src="button1a.gif">
</a> 


To make it possible for javascript to change the image we need to give it a name that can be used by javascript to address it. So in our case the HTML would look like this:
<a href="mypage.htm">
<Img Src="button1a.gif" 
name="button1">
</a>


Now the button has a name that can be used as a reference when we want javascript to replace it with another image. We need to tell the browser that once a mouse is rolled over the image, the browser should execute a function that replaces the image. This is done with the
onMouseOver event. In addition we also need to tell the browser that once the user rolls the mouse away from the image, another javascript should be solved in order to let the initial image of the button return. This is done with the onMouseOut event.The final HTML code looks like this:
<a href="mypage.htm" onmouseOver="MouseOverRoutine('button1')" onmouseOut="MouseOutRoutine('button1')">
<Img Src="button1a.gif" name="button1" ></a>

This is all you need to do in the HTML part of the page. The rest is done in javascript.

Note: The mouse events are added to the <a href> tag - NOT the image tag. This is because browsers do not look for mouseover events on images. As stupid as it may sound it is nevertheless true. Therefore we can only make images animated by turning them into links. Since browsers understand mouseover events on links, they will register a mouse event on an image, if that image is a link. 
THE JAVASCRIPT CODE

The following javascript should be added to the head part of your webpage. 
<Script>


<!--
// The previous line hides the script from
// old browsers that can't interpret it


// Assuming the image of the up button is called "button1a.gif"
// And that the image of the down button is called "button1b.gif"
// We can now read these two images into variables
// called button1up and button1down.


button1up = new Image; button1up.src = "button1a.gif";
button1down = new Image; button1down.src = "button1b.gif";

// Now the two images are defined.

// Next step is the two functions needed.
// The first function is called MouseOverRoutine,
// and causes button1up to shift to button1down.


function MouseOverRoutine(ButtonName)
{
if (ButtonName=="button1")
{document.button1.src = button1down.src;}
}

// Now our button will shift from button1up to button1down
// when a mouseover event occurs.
// To complete the script all we need to do
// is make the inverse function, that will do exactly the opposite
// when a mouseout event occurs.


function MouseOutRoutine(ButtonName)
{
if (ButtonName=="button1")
{document.button1.src = button1up.src;}
}

// Thats all there is.
// The final step is ending the script section which is done by two lines:


// The next line causes oldfashion browsers to
// start interpreting the code again.

//-->

</script>


If you want more than one button on your page, all you need to do is double each line referring to button1 and change it to button2, button3 or whatever number of buttons you might have.

3) FORM VALIDATION:

THE TECHNIQUE:

The javascript to validate inputs to a form consists of four different functions:
  • Emailvalidation will check to see if a value lives up to the general syntax of an email.
  • Valuevalidation will check to see if a value is within a certain interval.
  • Digitvalidation will check to see if a value consits of a certain number of digits. 
  • Emptyvalidation will check to see if a field is empty or not.
The validation can take place as the visitor enters values, or all at once upon clicking the submit button after entering the values. Each validation function can easily be customized to fit the needs of the fields they are checking.
THE CODE:
The script explained on this page actually consists of the four functions listed below:
·         emailvalidation(this,text)
·         valuevalidation(this,min,max,text,type)
·         digitvalidation(this,min,max,text,type)
·         emptyvalidation(this,text)
You can either validate each field whenever it is changed or you can validate all fields at one time when the submit button is clicked. At the last half of this page you can learn how to use either of these methods along with the scripts.First, let's look at the different validation scripts.

emailvalidation(this,text)
Checking if the content has the general syntax of an email.
Optional parameters are:
text--text that will show in an alertbox if content is illegal.
function emailvalidation(entered, alertbox)
{
// E-mail Validation by Henrik Petersen / NetKontoret
// Explained at www.echoecho.com/jsforms.htm
// Please do not remove this line and the two lines above.
with (entered)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
lastpos=value.length-1;
if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2)
{if (alertbox) {alert(alertbox);} return false;}
else {return true;}
}

valuevalidation(this,min,max,text,type)
Checking if the content is a number in a limited area.
Optional parameters are:
min --minimum value allowed in the field.
max --maximum value allowed in the field.
text --text that will show in an alertbox if content is illegal.
type --enter "I" if only integers are allowed.
function valuevalidation(entered, min, max, alertbox, datatype)
{
// Value Validation by Henrik Petersen / NetKontoret
// Explained at www.echoecho.com/jsforms.htm
// Please do not remove this line and the two lines above.
with (entered)
{
checkvalue=parseFloat(value);
if (datatype)
{smalldatatype=datatype.toLowerCase();
if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value)};
}
if ((parseFloat(min)==min && checkvalue<min) || (parseFloat(max)==max && checkvalue>max) || value!=checkvalue)
{if (alertbox!="") {alert(alertbox);} return false;}
else {return true;}
}
digitvalidation(this,min,max,text,type)
Checking if the content has a certain number of digits.
Optional parameters are:
min --minimum number of digits allowed in the field.
max --maximum number of digits allowed in the field.
text --text that will show in an alertbox if content is illegal.
type --enter "I" if only integers are allowed.

function digitvalidation(entered, min, max, alertbox, datatype)
{
// Digit Validation by Henrik Petersen / NetKontoret
// Explained at www.echoecho.com/jsforms.htm
// Please do not remove this line and the two lines above.
with (entered)
{
checkvalue=parseFloat(value);
if (datatype)
{smalldatatype=datatype.toLowerCase();
if (smalldatatype.charAt(0)=="i")
{checkvalue=parseInt(value); if (value.indexOf(".")!=-1) {checkvalue=checkvalue+1}};
}
if ((parseFloat(min)==min && value.length<min) || (parseFloat(max)==max && value.length>max) || value!=checkvalue)
{if (alertbox!="") {alert(alertbox);} return false;}
else {return true;}
}
emptyvalidation(this,text)
Checking if the field is empty.
Optional parameters are:
text --text that will show in an alertbox if content is illegal.
function emptyvalidation(entered, alertbox)
{
// Emptyfield Validation by Henrik Petersen / NetKontoret
// Explained at www.echoecho.com/jsforms.htm
// Please do not remove this line and the two lines above.
with (entered)
{
if (value==null || value=="")
{if (alertbox!="") {alert(alertbox);} return false;}
else {return true;}
}

Note:
All functions require 
this to be entered as a parameter.
Simply enter the word "
this" as a parameter when calling one of the functions. This will pass the content of the current field to the function.

If 
text is not entered when you call the function, it will not launch a popup box if an error is detected. However, the function will still return the value "false". This option is used when we check for several possible errors at one time. That is: when all fields are checked once the submit button is clicked.
USING THE VALIDATION SCRIPTS

There are two different ways to call these functions. One is used when you want to check the field immediately after an input is made to it. The other is when you want to check all fields at one time, when the user clicks the submit button.
onChange Validation:
To force the browser to check each field immediately, we add an onChange to each of the <input> tags in the form.For example: if we wanted to check if the value of a certain text field had a valid e-mail address we would add this:
<input type="text" name="Email" size="20" onChange="emailvalidation(this,'The E-mail is not valid');"> 

onSubmit Validation:
You might prefer to check all fields at one time when the user hits the submit button.
To do this you should add an 
onSubmit event handler to the <form>tag. If, for example you have a form called "myform" and you want all fields checked when the user clicks 'submit' you should create a function that checks all the fields.This function should then be called by an onSubmit-event added to the <form>tag.If this function was called "formvalidation()" the <form> tag would look like this:
<form onsubmit="return formvalidation(this)"> 


The function that checks the entire form will either return a value of false or true. If it's true the form will be submitted - if it's false the submission will be cancelled. A script that checks all fields in a form could look like this:
function formvalidation(thisform)
This function checks the entire form before it is submitted.
function formvalidation(thisform)
{
with (thisform)
{
if (emailvalidation(
Email,"Illegal E-mail")==false) {Email.focus(); return false;};
if (valuevalidation(
Value,0,5,"Value MUST be in the range 0-5")==false) {Value.focus(); return false;};
if (digitvalidation(
Digits,3,4,"You MUST enter 3 or 4 integer digits","I")==false) {Digits.focus(); return false;};
if (emptyvalidation(
Whatever,"The textfield is empty")==false) {Whatever.focus(); return false;};
}

Note:
The above function works in addition to the four functions listed at the top of this page.
Furthermore, the function needs to be customized to fit your form.You will need to enter the appropriate form field names used on your own form. (Instead of "
E-mail", "Value", "Digits" and "Whatever" in this example). Furthermore you would need to call the appropriate functions depending on which check you would like to perform on each form field. (In the example each field is checked by a different function. You could as well have each field checked by the same function. If for example the form had 4 fields that should all contain an e-mail address you would add an emailvalidation to each. )

 

EXAMPLE:


<script>

function emailvalidation(entered, alertbox)
{
// E-mail Validation by Henrik Petersen / NetKontoret
// Explained at www.echoecho.com/jsforms.htm
// Please do not remove this line and the two lines above.
with (entered)
{
apos=value.indexOf("@");
dotpos=value.lastIndexOf(".");
lastpos=value.length-1;
if (apos<1 || dotpos-apos<2 || lastpos-dotpos>3 || lastpos-dotpos<2)
{if (alertbox) {alert(alertbox);} return false;}
else {return true;}
}
}

function valuevalidation(entered, min, max, alertbox, datatype)
{
// Value Validation by Henrik Petersen / NetKontoret
// Explained at www.echoecho.com/jsforms.htm
// Please do not remove this line and the two lines above.
with (entered)
{
checkvalue=parseFloat(value);
if (datatype)
{smalldatatype=datatype.toLowerCase();
if (smalldatatype.charAt(0)=="i") {checkvalue=parseInt(value)};
}
if ((parseFloat(min)==min && checkvalue<min) || (parseFloat(max)==max && checkvalue>max) || value!=checkvalue)
{if (alertbox!="") {alert(alertbox);} return false;}
else {return true;}
}
}


function digitvalidation(entered, min, max, alertbox, datatype)
{
// Digit Validation by Henrik Petersen / NetKontoret
// Explained at www.echoecho.com/jsforms.htm
// Please do not remove this line and the two lines above.
with (entered)
{
checkvalue=parseFloat(value);
if (datatype)
{smalldatatype=datatype.toLowerCase();
if (smalldatatype.charAt(0)=="i")
{checkvalue=parseInt(value); if (value.indexOf(".")!=-1) {checkvalue=checkvalue+1}};
}
if ((parseFloat(min)==min && value.length<min) || (parseFloat(max)==max && value.length>max) || value!=checkvalue)
{if (alertbox!="") {alert(alertbox);} return false;}
else {return true;}
}
}


function emptyvalidation(entered, alertbox)
{
// Emptyfield Validation by Henrik Petersen / NetKontoret
// Explained at www.echoecho.com/jsforms.htm
// Please do not remove this line and the two lines above.
with (entered)
{
if (value==null || value=="")
{if (alertbox!="") {alert(alertbox);} return false;}
else {return true;}
}
}


function formvalidation(thisform)
{
// This function checks the entire form before it is submitted
// Note: This function needs to be customized to fit your form
with (thisform)
{
if (emailvalidation(Email,"Illegal E-mail")==false) {Email.focus(); return false;};
if (valuevalidation(Value,0,5,"Value MUST be in the range 0-5")==false) {Value.focus(); return false;};
if (digitvalidation(Digits,3,4,"You MUST enter 3 or 4 integer digits","I")==false) {Digits.focus(); return false;};
if (emptyvalidation(Whatever,"The textfield is empty")==false) {Whatever.focus(); return false;};
}
}
</script>

 

4)    MULTIPLE LINKS:

THE TECHNIQUE:

This script will let us open two or more pages when a single link is clicked. First we neutralize the html link. This is done by letting the link point to "#" which means it points to nowhere and thus has no effect in HTML. The trick is, that at the same time, we add an onClick event to the link. This event will, in return, execute our small javascript that opens the two pages. In this article we will limit the script to open two pages. But as we said, the technique can easily be used to open as many pages as you like from a single link. 

THE CODE:
Assuming you want a link to open Yahoo in a frame called bannerframe and AltaVista in a frame called mainframe the code looks like this:
<a href="#" onClick="
parent.
bannerframe.location='http://www.Yahoo.com';
parent.
mainframe.location='http://www.altavista.com';
return false;
">


As you can see, we simply add a: parent.
framename.location='linkname'; for each page we want to open. You can, of course, add as many links as you like.

NOTE: The 
onClick event is enclosed by double quotes. The javascript links are enclosed by single quotes.

The 
return false statement makes sure that the browser doesn't even try to interpret the html link (pointing to #). This is necessary because sometimes a link to an unexisting anchor forces the browser to go to the top of the page (which might not be what we want).
5) http://www.echoecho.com/p.gifCOOKIES:
A cookie is simply a variable that your webpage can store on or retrieve from the user's computer. The idea is that the next time the user arrives at your page, the value of the cookie can be read by your page, and then used for whatever purpose you choose.Examples of cookies could be: 
  • First time the visitor arrives the name is entered. (for example "John Wayne").
    The username is then stored in a cookie.  Next time he arrives at your page, it writes something like:  "Welcome to my page John Wayne!! Good to see you again".
    The name is simply retrieved from the stored cookie.
  • First time the user arrives at your page she enters the desired language.
    The chosen language is stored in a cookie.
    Next time she visits your site, she will simply be taken to the pages in the desired language without asking, since the desired language is retrieved from the cookie.
  • First time the user arrives at your page he is asked to fill in a password.
    The password is saved in a cookie. Next time he arrives at your page, the password is retrieved from the cookie.

THE TECHNIQUE:

Cookies can be stored and retrieved using javascript. The script first checks to see if a cookie has already been set.
  • If so, it uses the cookie for some purpose.
  • If not, it sets a cookie and uses it the next time the user arrives at the page.
Cookies are stored until a specified expiration date. If a cookie is present when a user arrives at your page it is stored in thedocument.cookie object. This article will teach you how to read the cookie from the document.cookieobject, as well as how to specify the variables used in the setCookie command.

THE CODE:

http://www.echoecho.com/p.gifIn order to use cookies on a page you need:
·   a function that reads the cookie (if present)
·   a function that stores the cookie
·   a function that deletes the cookie
Below are three functions that perform these tasks:
·         getCookie
·         setCookie
·         delCookie
function getCookie(NameOfCookie)
{

// First we check to see if there is a cookie stored.
// Otherwise the length of document.cookie would be zero.


if (document.cookie.length > 0)
{

// Second we check to see if the cookie's name is stored in the
// "document.cookie" object for the page.

// Since more than one cookie can be set on a
// single page it is possible that our cookie
// is not present, even though the "document.cookie" object
// is not just an empty text.
// If our cookie name is not present the value -1 is stored
// in the variable called "begin".


begin = document.cookie.indexOf(NameOfCookie+"=");
if (begin != -1) // Note: != means "is not equal to"
{

// Our cookie was set.
// The value stored in the cookie is returned from the function.


begin += NameOfCookie.length+1;
end = document.cookie.indexOf(";", begin);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(begin, end)); }
}
return null;

// Our cookie was not set.
// The value "null" is returned from the function.


}
function setCookie(NameOfCookie, value, expiredays)
{

// Three variables are used to set the new cookie.
// The name of the cookie, the value to be stored,
// and finally the number of days until the cookie expires.
// The first lines in the function convert
// the number of days to a valid date.


var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));

// The next line stores the cookie, simply by assigning
// the values to the "document.cookie" object.
// Note the date is converted to Greenwich Mean time using
// the "toGMTstring()" function.


document.cookie = NameOfCookie + "=" + escape(value) +
((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}
function delCookie (NameOfCookie)
{

// The function simply checks to see if the cookie is set.
// If so, the expiration date is set to Jan. 1st 1970.


if (getCookie(NameOfCookie)) {
document.cookie = NameOfCookie + "=" +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
MAKING IT WORK
Simply adding the above code to a page does not set any cookies. The functions are the tools you need in order to read, set, and delete cookies on your page. The final step in adding a cookie to your page is to add a purpose to the cookie. Decide whether you want the cookie to store the user's name, the date of his last visit to your page or the preferred language. Or use the cookie for whatever purpose you wish. In any case, the codes you need to add to the cookie scripts will be different.
RAW SCRIPT
Below is the cookie script without the comments. Copy and paste to use the script on your own site.
function getCookie(NameOfCookie)
{ if (document.cookie.length > 0)
{ begin = document.cookie.indexOf(NameOfCookie+"=");
if (begin != -1)
{ begin += NameOfCookie.length+1;
end = document.cookie.indexOf(";", begin);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(begin, end)); }
}
return null;
}



function setCookie(NameOfCookie, value, expiredays)
{ var ExpireDate = new Date ();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
document.cookie = NameOfCookie + "=" + escape(value) +
((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}



function delCookie (NameOfCookie)
{ if (getCookie(NameOfCookie)) {
document.cookie = NameOfCookie + "=" +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

}

6)    FRAMESET SCRIPT:

Javascript can be a powerful addition to frames pages. One of the biggest disadvantages of frame based websites has been that you could not refer to your subpages, unless you wanted the visitor to open it oustside the frameset. With javascript, you can create subpages that - if loaded outside the frameset - will load themselves into the frameset. That's what the rest of this article is about.

THE TECHNIQUE:

This script ensures that subpages aren't loaded outside a frameset. If a visitor enters the url of a subpage - the script will make sure that the frameset is loaded with the subpage in one of the frames. We will need to enter a small script on both the frameset page and each of the subpages. What actually happens is this: If a subpage is loaded outside the frameset, the script on the subpage will detect it and load the frameset instead. Once the frameset is loaded, the script on the frameset page will load the referring subpage into the correct frame window.

THE CODE:
As mentioned on the previous page, you need to enter a small script in the<head> section of both your subpages and your frameset page.
THE CODE FOR THE SUB PAGES
The script to copy and paste to the <HEAD>-section of your subpages looks like this:

<HEAD>

<script>
function detect()
{
framesetpage="myframeset.htm";
thispage=window.location.href;
if (thispage.indexOf('://')<0) {thispage="://"+thispage;};
prefix=thispage.substring(0,thispage.lastIndexOf('://'));
suffix=thispage.substring(thispage.lastIndexOf('://')+3,thispage.length);
// alert('the subpage is:['+prefix+']['+suffix+']');
if (parent.location.href==window.location.href) {parent.location.href=framesetpage+"?"+prefix+"&&&"+suffix};
}
</script>

</HEAD>


Customize this line to fit your own pages (replace myframeset.htm with the name of your own frameset page.): 
framesetpage="myframeset.htm";

In addition to adding the above script, you also need to add an onLoad-event to the <BODY>-tag.
<BODY onLoad="detect()">

That's it. After adding this piece of code to each of your subpages you're can proceed to the final step: adding a code-piece to the frameset-page itself.Before describing the code to add to the frameset-page, we will explain how the code for the subpages works.
HOW IT WORKS

This line detects if the page is loaded into a frameset:
if (parent.location.href==window.location.href) 


parent.location.href returns the url of the parent frame.
window.location.href returns the url of the current page.

Now, if these two are the similar it means that there are no parent frames: the current page is the top page.In that case, this line is executed:
parent.location.href=framesetpage+"?"+prefix+"&&&"+suffix; 


It opens the frameset page similar to if you had entered http://www.yourdomain.com/framespage.htm?http&&&www.yourdomain.com/subpage.htm in the url box of your browser. The trick of this entire script is that the script on the framespage can access the entry that follows the ? through the javascript built-in
window.location.search object. That is how the information is passed to tell the frameset page which subpage to load.
THE CODE FOR THE FRAMESET PAGE
This is the script to copy and paste to the frames page:

<HTML>
<HEAD>
<TITLE>MyFramesPage</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
defaultsubpage="defaultsub.htm";
if (location.search) {subpage=location.search.substring(1)}
else {subpage=defaultsubpage}
if (subpage.indexOf('&&&')>=0) {
prefix=subpage.substring(0,subpage.indexOf('&&&'))+"://";
suffix=subpage.substring(subpage.indexOf('&&&')+3,subpage.length);
subpage=prefix+suffix;
}
// -->
</SCRIPT>

</HEAD>

<SCRIPT>
document.write('<FRAMESET COLS="50%,50%">');
document.write('<FRAME SRC="navpage.htm" NAME="nav">');
document.write('<FRAME SRC="'+subpage+'" NAME="main">');
document.write('</FRAMESET>');
</SCRIPT>

</HTML>
Customize the frameset values to fit your own page.You need to customize this one line:
defaultsubpage="defaultsub.htm";

Replace defaultsub.htm with the name of your own default page for the frameset. Also note, that in this line:
document.write('<FRAME SRC="'+subpage+'" NAME="main">');

main is the name of the "intelligent" frame. You can pick any name you want for the frame, we just used the name main for our example. 
HOW IT WORKS
These lines detects if a value was passed to the frameset page following a ? in the url:
if (location.search) {subpage=location.search.substring(1)}
else {subpage=defaultsubpage}

If a value was entered after a ? in the url, then the script returns the value. Otherwise it returns the name you entered for the default page to load (in our example it would be "defaultsub.htm"). Now, if this page was called from a subpage that was loaded outside of the frameset, then the url would look something like this:  http://www.yourdomain.com/framespage.htm?http&&&www.yourdomain.com/subpage.htm
For technical reasons the subpage doesn't pass the URL of the subpage as is. It uses &&& instead of the normal :// that you usually see in a URL. (The reason is that netscape can't pass these values in a querystring). This url based on &&& is translated into a real url by these lines at the top of our script:
if (subpage.indexOf('&&&')>=0) {
prefix=subpage.substring(0,subpage.indexOf('&&&'))+"://";
suffix=subpage.substring(subpage.indexOf('&&&')+3,subpage.length);
subpage=prefix+suffix;
}

The final part of our script is the document.write lines that writes the HTML for the frameset.
document.write('<FRAMESET COLS="50%,50%">');
document.write('<FRAME SRC="navpage.htm" NAME="nav">');
document.write('<FRAME SRC="'+
subpage+'" NAME="main">');
document.write('</FRAMESET>');

The variable subpage either contains the url of the default page or - if the frameset was launched by a subpage - the url of the subpage to load into the "intelligent" frame.

7) DROP-DOWN MENU:

THE TECHNIQUE:

Each field in the drop-down menu has a name that will show in the menu. The value attached to each of the fields are the URLs that should be called when the option is selected. By adding onChange="DropDownMenu(this)" to the <select> tags we force the browser to run our script when a field is picked from a menu. The script then reads which option is picked, and loads the referring page. It is possible to add a target to the URL which means that the referring page can either be loaded into the same window, into a specific frame, or into a new window.

THE CODE:

To make this script work on your page you need to add it to the <head> section of your document. Next you need to add onChange="DropDownMenu(this)" to each drop-down menu that should call the script. The onChange is added to the <select> tag of the desired
drop-down menu. Finally you need to add the desired URL and the optional target to each of the options in the menus. To do this use the following syntax:

<option value="http://www.yahoo.com">Yahoo</option> 

If you want to add a target to the link use this syntax:

<option value="http://www.yahoo.com&target">Yahoo</option> 

where "target" is replaced by the target you want to use.If you wanted the link to open in a frame called "main" you would add:

<option value="http://www.yahoo.com&main">Yahoo</option> 

Note: You can also use the reserved targets:
·         "_blank"
·         "_top"
·         "_parent"
·         "_self"
Click here to get an explanation of these targets. Finally, you can enter FALSE in the URL field to let the script know that the option shouldn't load a page. This is what you do if you want one of the options to be a header for the drop-down menu - for example "SEARCH ENGINES" and "THIS SITE" in the two examples shown at the top of this page. The script looks like this:

<script>
function DropDownMenu(entered)
{
// *********************************
// DROP DOWN MENU (c) Henrik Petersen / NetKontoret 1998 - All rights reserved
// Explained along with other useful scripts at: http://www.echoecho.com/javascript.htm
// You may freely use this script as long as you do not remove this line and the 2 lines above.
// ****************************************** 

with (entered)
{
// Store the selected option in a variable called ref
ref=options[selectedIndex].value;
// Count the position of the optional &
splitcharacter=ref.lastIndexOf("&");

// The three lines below checks if a target goes along with the URL
// That is: (if a "&" is in the option-value).
// If so, the URL is stored in a variable called loc and the target
// is stored in a variable called target.
// If not the URL is stored in a variable called loc and "_self" is
// stored in the variable called target.

if (splitcharacter!=-1) {loc=ref.substring(0,splitcharacter); target=ref.substring(splitcharacter+1,1000).toLowerCase();}
else {loc=ref; target="_self";};

// create a varible called lowloc to store loc in lowercase characters.
lowloc=loc.toLowerCase();

// Skip the rest of this function if the selected optionvalue is "false".
if (lowloc=="false") {return;}

// Open link in current document
if (target=="_self") {document.location=loc;}

// Cancel eventual framesets and open link in current window
else {if (target=="_top") {top.location=loc;}

// Open link in new window
else {if (target=="_blank") {window.open(loc);}

// Open link in parent frame
else{if (target=="_parent") {parent.location=loc;}

// Open link in the specified frame
else {parent.frames[target].location=loc;};
}}}}
}
</script>

 

EXAMPLE:


<script>
function DropDownMenu(entered)
{
// ***************************************************************************
// DROP DOWN MENU (c) Henrik Petersen / NetKontoret 1998 - All rights reserved 
// Explained along with other useful scripts at: http://www.echoecho.com/javascript.htm
// You may freely use this script as long as you do not remove this line and the 2 lines above.
// ***************************************************************************
with (entered)
{
ref=options[selectedIndex].value;
 
splitcharacter=ref.lastIndexOf("&");
 
if (splitcharacter!=-1) {loc=ref.substring(0,splitcharacter); target=ref.substring(splitcharacter+1,1000).toLowerCase();}
else {loc=ref; target="_self";};
lowloc=loc.toLowerCase();
 
if (lowloc=="false") {return;}
 
if (target=="_self") {document.location=loc;}
 
else {if (target=="_top") {top.location=loc;}
 
else {if (target=="_blank") {window.open(loc);}
 
else{if (target=="_parent") {parent.location=loc;}
else {parent.frames[target].location=loc;};
 
}}}}
}
</script>
 

 

8)    POPUP WINDOWS:

THE TECHNIQUE:

JavaScript has built-in methods for opening and closing windows.The window.open method lets you open a new window in a much more powerful way than if you had opened it with plain HTML using target="blank". You can specify the size of the new window. Furthermore you can specify which browser buttons and menus etc. you want to appear in the new window. Finally you can even control the position of the new window.

THE CODE:

When working with popup windows, three different techniques are relevant:
·         HOW TO OPEN A WINDOW
·         HOW TO CLOSE A WINDOW
·         HOW TO CUSTOMIZE A WINDOW

This page covers these techniques one by one.
OPEN WINDOW

The basic javascript to open a new window is:
MyNewWindow=
window.open("http://www.mydomain.com/myfile.html", "NameOfMyWindow"); 

This will open a new window similar to the one described on the previous page. We still haven't set any conditions for the size of the window or which of the browsers menus and buttons we want to be present.

CLOSE WINDOW

The javascript to close the window is:
NameOfMyWindow.close(); 

NameOfMyWindow is the name you assigned to the window when you opened it.

Note:If you want to close the current active window you do not need to specify the window name.

Instead you can simply use:

window.close();

CUSTOMIZING A WINDOW

You can add several parameters for the new window. This will allow you to control the size as well as which parts of the browser should be available in the window.
option
explanation 
toolbar = yes | no
add/remove browsers toolbar 
location = yes | no
add/remove browsers location field 
directories = yes | no
add/remove browsers directories field 
status = yes | no
add/remove browsers status field 
menubar = yes | no
add/remove browsers menubar 
scrollbars = yes | no
add/remove browsers scrollbars 
resizeable = yes | no
allow new window to be resizable 
width = value
window width in pixels 
height = value
window height in pixels 

An example showing the way to define which parts of the browser should be visible is shown below:
PageURL="http://www.mydomain.com/myfile.html";

WindowName="MyPopUpWindow";

settings=
"toolbar=yes,location=yes,directories=yes,"+
"status=no,menubar=no,scrollbars=yes,"+
"resizable=yes,width=600,height=300";


MyNewWindow=
window.open(PageURL,WindowName,
settings); 

Note:
There are no spaces between the settings. If you add spaces here, the window will not open correctly in Netscape browsers.