JavaScript – Samples

What is JavaScript ?

JavaScript started life as LiveScript, but Netscape changed the name, possibly because of the excitement being generated by Java.to JavaScript. JavaScript made its first appearance in Netscape 2.0 in 1995 with a name LiveScript.

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.

The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers

The ECMA-262 Specification defined a standard version of the core JavaScript language.

JavaScript is:

  • JavaScript is a lightweight, interpreted programming language
  • Designed for creating network-centric applications
  • Complementary to and integrated with Java
  • Complementary to and integrated with HTML
  • Open and cross-platform

Client-side JavaScript:

Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser.

It means that a web page need no longer be static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism features many advantages over traditional CGI server-side scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are valid they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user explicitly or implicitly initiates.

Advantages of JavaScript:

The merits of using JavaScript are:

  • Less server interaction: You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
  • Immediate feedback to the visitors: They don’t have to wait for a page reload to see if they have forgotten to enter something.
  • Increased interactivity: You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
  • Richer interfaces: You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

Limitations with JavaScript:

We can not treat JavaScript as a full fledged programming language. It lacks the following important features:

  • Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reason.
  • JavaScript can not be used for Networking applications because there is no such support available.
  • JavaScript doesn’t have any multithreading or multiprocess capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows you to build interactivity into otherwise static HTML pages.

JavaScript Development Tools:

One of JavaScript’s strengths is that expensive development tools are not usually required. You can start with a simple text editor such as Notepad.

Since it is an interpreted language inside the context of a web browser, you don’t even need to buy a compiler.

To make our life simpler, various vendors have come up with very nice JavaScript editing tools. Few of them are listed here:

  • Microsoft FrontPage: Microsoft has developed a popular HTML editor called FrontPage. FrontPage also provides web developers with a number of JavaScript tools to assist in the creation of an interactive web site.
  • Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very popular HTML and JavaScript editor in the professional web development crowd. It provides several handy prebuilt JavaScript components, integrates well with databases, and conforms to new standards such as XHTML and XML.
  • Macromedia HomeSite 5: This provided a well-liked HTML and JavaScript editor, which will manage their personal web site just fine.

Where JavaScript is Today ?

The ECMAScript Edition 4 standard will be the first update to be released in over four years. JavaScript 2.0 conforms to Edition 4 of the ECMAScript standard, and the difference between the two is extremely minor.

The specification for JavaScript 2.0 can be found on the following site:http://www.ecmascript.org/

Today, Netscape’s JavaScript and Microsoft’s JScript conform to the ECMAScript standard, although each language still supports features that are not part of the standard.

A JavaScript consists of JavaScript statements that are placed within the <script>… </script> HTML tags in a web page.

You can place the <script> tag containing your JavaScript anywhere within you web page but it is preferred way to keep it within the <head> tags.

The <script> tag alert the browser program to begin interpreting all the text between these tags as a script. So simple syntax of your JavaScript will be as follows

<script ...>
  JavaScript code
</script>

The script tag takes two important attributes:

  • language: This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
  • type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to “text/javascript”.

So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">
  JavaScript code
</script>

Your First JavaScript Script:

Let us write our class example to print out “Hello World”.

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
   document.write("Hello World!")
//-->
</script>
</body>
</html>

We added an optional HTML comment that surrounds our Javascript code. This is to save our code from a browser that does not support Javascript. The comment ends with a “//–>”. Here “//” signifies a comment in Javascript, so we add that to prevent a browser from reading the end of the HTML comment in as a piece of Javascript code.

Next, we call a function document.write which writes a string into our HTML document. This function can be used to write text, HTML, or both. So above code will display following result:

Hello World!

Whitespace and Line Breaks:

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.

Because you can use spaces, tabs, and newlines freely in your program so you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

Semicolons are Optional:

Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if your statements are each placed on a separate line. For example, the following code could be written without semicolons

<script language="javascript" type="text/javascript">
<!--
  var1 = 10
  var2 = 20
//-->
</script>

But when formatted in a single line as follows, the semicolons are required:

<script language="javascript" type="text/javascript">
<!--
  var1 = 10; var2 = 20;
//-->
</script>

Note: It is a good programming practice to use semicolons.

Case Sensitivity:

JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

So identifiers TimeTIme and TIME will have different meanings in JavaScript.

NOTE: Care should be taken while writing your variable and function names in JavaScript.

Comments in JavaScript:

JavaScript supports both C-style and C++-style comments, Thus:

  • Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
  • Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
  • JavaScript also recognizes the HTML comment opening sequence <!–. JavaScript treats this as a single-line comment, just as it does the // comment.
  • The HTML comment closing sequence –> is not recognized by JavaScript so it should be written as //–>.

Example:

<script language="javascript" type="text/javascript">
<!--

// This is a comment. It is similar to comments in C++

/*
 * This is a multiline comment in JavaScript
 * It is very similar to comments in C Programming
 */
//-->
</script>

There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are following most preferred ways to include JavaScript in your HTML file.

  • Script in <head>…</head> section.
  • Script in <body>…</body> section.
  • Script in <body>…</body> and <head>…</head> sections.
  • Script in and external file and then include in <head>…</head> section.

In the following section we will see how we can put JavaScript in different ways:

JavaScript in <head>…</head> section:

If you want to have a script run on some event, such as when a user clicks somewhere, then you will place that script in the head as follows:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

JavaScript in <body>…</body> section:

If you need a script to run as the page loads so that the script generates content in the page, the script goes in the <body> portion of the document. In this case you would not have any function defined using JavaScript:

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

JavaScript in <body> and <head> sections:

You can put your JavaScript code in <head> and <body> section altogether as follows:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
To understand it in better way you can Try it yourself.

JavaScript in External File :

As you begin to work more extensively with JavaScript, you will likely find that there are cases where you are reusing identical JavaScript code on multiple pages of a site.

You are not restricted to be maintaining identical code in multiple HTML files. The script tag provides a mechanism to allow you to store JavaScript in an external file and then include it into your HTML files.

Here is an example to show how you can include an external JavaScript file in your HTML code using script tag and its src attribute:

<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>

To use JavaScript from an external file source, you need to write your all JavaScript source code in a simple text file with extension “.js” and then include that file as shown above.

For example, you can keep following content in filename.js file and then you can use sayHellofunction in your HTML file after including filename.js file:

function sayHello() {
   alert("Hello World")
}

JavaScript DataTypes:

One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language.

JavaScript allows you to work with three primitive data types:

  • Numbers eg. 123, 120.50 etc.
  • Strings of text e.g. “This text string” etc.
  • Boolean e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value.

In addition to these primitive data types, JavaScript supports a composite data type known asobject. We will see an object detail in a separate chapter.

Note: Java does not make a distinction between integer values and floating-point values. All numbers in JavaScript are represented as floating-point values. JavaScript represents numbers using the 64-bit floating-point format defined by the IEEE 754 standard.

JavaScript Variables:

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows:

<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>

You can also declare multiple variables with the same var keyword as follows:

<script type="text/javascript">
<!--
var money, name;
//-->
</script>

Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or later point in time when you need that variable as follows:

For instance, you might create a variable named money and assign the value 2000.50 to it later. For another variable you can assign a value the time of initialization as follows:

<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>

Note: Use the var keyword only for declaration or initialization.once for the life of any variable name in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don’t have to tell JavaScript during variable declaration what type of value the variable will hold. The value type of a variable can change during the execution of a program and JavaScript takes care of it automatically.

JavaScript Variable Scope:

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.

  • Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code.
  • Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Following example explains it:

<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
   var myVar = "local";  // Declare a local variable
   document.write(myVar);
}
//-->
</script>

This produces the following result:

local

JavaScript Variable Names:

While naming your variables in JavaScript keep following rules in mind.

  • You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
  • JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but_123test is a valid one.
  • JavaScript variable names are case sensitive. For example, Name and name are two different variables.

JavaScript Reserved Words:

The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.

abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with

_________________________________________________________________________

What is an operator?

Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. JavaScript language supports following type of operators.

  • Arithmetic Operators
  • Comparision Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators

Lets have a look on all operators one by one.

The Arithmatic Operators:

There are following arithmatic operators supported by JavaScript language:

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example
+ Adds two operands A + B will give 30
Subtracts second operand from the first A – B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
Decrement operator, decreases integer value by one A– will give 9

Note: Addition operator (+) works for Numeric as well as Strings. e.g. “a” + 10 will give “a10”.

To understand these operators in better way you can Try it yourself.

The Comparison Operators:

There are following comparison operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example
== Checks if the value of two operands are equal or not, if yes then condition becomes true. (A == B) is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.

The Logical Operators:

There are following logical operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example
&& Called Logical AND operator. If both the operands are non zero then then condition becomes true. (A && B) is true.
|| Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is false.

The Bitwise Operators:

There are following bitwise operators supported by JavaScript language

Assume variable A holds 2 and variable B holds 3 then:

Operator Description Example
& Called Bitwise AND operator. It performs a Boolean AND operation on each bit of its integer arguments. (A & B) is 2 .
| Called Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments. (A | B) is 3.
^ Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. (A ^ B) is 1.
~ Called Bitwise NOT Operator. It is a is a unary operator and operates by reversing all bits in the operand. (~B) is -4 .
<< Called Bitwise Shift Left Operator. It moves all bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc. (A << 1) is 4.
>> Called Bitwise Shift Right with Sign Operator. It moves all bits in its first operand to the right by the number of places specified in the second operand. The bits filled in on the left depend on the sign bit of the original operand, in order to preserve the sign of the result. If the first operand is positive, the result has zeros placed in the high bits; if the first operand is negative, the result has ones placed in the high bits. Shifting a value right one place is equivalent to dividing by 2 (discarding the remainder), shifting right two places is equivalent to integer division by 4, and so on. (A >> 1) is 1.
>>> Called Bitwise Shift Right with Zero Operator. This operator is just like the >> operator, except that the bits shifted in on the left are always zero, (A >>> 1) is 1.

The Assignment Operators:

There are following assignment operators supported by JavaScript language:

Operator Description Example
= Simple assignment operator, Assigns values from right side operands to left side operand C = A + B will assigne value of A + B into C
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand C += A is equivalent to C = C + A
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand C -= A is equivalent to C = C – A
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand C *= A is equivalent to C = C * A
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand C /= A is equivalent to C = C / A
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand C %= A is equivalent to C = C % A

Note: Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |= and ^=.

Miscellaneous Operator

The Conditional Operator (?🙂

There is an oprator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax:

Operator Description Example
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

The typeof Operator

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to “number”, “string”, or “boolean” if its operand is a number, string, or boolean value and returns true or false based on the evaluation.

Here is the list of return values for the typeof Operator :

Type String Returned by typeof
Number “number”
String “string”
Boolean “boolean”
Object “object”
Function “function”
Undefined “undefined”
Null “object”

While writing a program, there may be a situation when you need to adopt one path out of the given two paths. So you need to make use of conditional statements that allow your program to make correct decisions and perform right actions.

JavaScript supports conditional statements which are used to perform different actions based on different conditions. Here we will explain if..else statement.

JavaScript supports following forms of if..else statement:

  • if statement
  • if…else statement
  • if…else if… statement.

if statement:

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

Syntax:

if (expression){
   Statement(s) to be executed if expression is true
}

Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) are executed. If expression is false then no statement would be not executed. Most of the times you will use comparison operators while making decisions.

Example:

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
   document.write("<b>Qualifies for driving</b>");
}
//-->
</script>

This will produce following result:

Qualifies for driving

To understand it in better way you can Try it yourself.

if…else statement:

The if…else statement is the next form of control statement that allows JavaScript to execute statements in more controlled way.

Syntax:

if (expression){
   Statement(s) to be executed if expression is true
}else{
   Statement(s) to be executed if expression is false
}

Here JavaScript expression is evaluated. If the resulting value is true, given statement(s) in theif block, are executed. If expression is false then given statement(s) in the else block, are executed.

Example:

<script type="text/javascript">
<!--
var age = 15;
if( age > 18 ){
   document.write("<b>Qualifies for driving</b>");
}else{
   document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>

This will produce following result:

Does not qualify for driving

To understand it in better way you can Try it yourself.

if…else if… statement:

The if…else if… statement is the one level advance form of control statement that allows JavaScript to make correct decision out of several conditions.

Syntax:

if (expression 1){
   Statement(s) to be executed if expression 1 is true
}else if (expression 2){
   Statement(s) to be executed if expression 2 is true
}else if (expression 3){
   Statement(s) to be executed if expression 3 is true
}else{
   Statement(s) to be executed if no expression is true
}

There is nothing special about this code. It is just a series of if statements, where each if is part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if non of the condition is true then else block is executed.

Example:

<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
   document.write("<b>History Book</b>");
}else if( book == "maths" ){
   document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
   document.write("<b>Economics Book</b>");
}else{
  document.write("<b>Unknown Book</b>");
}
//-->
</script>

This will produce following result:

Maths Book

To understand it in better way you can Try it yourself.

You can use multiple if…else if statements, as in the previous chapter, to perform a multiway branch. However, this is not always the best solution, especially when all of the branches depend on the value of a single variable.

Starting with JavaScript 1.2, you can use a switch statement which handles exactly this situation, and it does so more efficiently than repeated if…else if statements.

Syntax:

The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, adefault condition will be used.

switch (expression)
{
  case condition 1: statement(s)
                    break;
  case condition 2: statement(s)
                    break;
   ...
  case condition n: statement(s)
                    break;
  default: statement(s)
}

The break statements indicate to the interpreter the end of that particular case. If they were omitted, the interpreter would continue executing each statement in each of the following cases.

We will explain break statement in Loop Control chapter.

Example:

Following example illustrates a basic while loop:

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
  case 'A': document.write("Good job<br />");
            break;
  case 'B': document.write("Pretty good<br />");
            break;
  case 'C': document.write("Passed<br />");
            break;
  case 'D': document.write("Not so good<br />");
            break;
  case 'F': document.write("Failed<br />");
            break;
  default:  document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

This will produce following result:

Entering switch block
Good job
Exiting switch block

To understand it in better way you can Try it yourself.

Example:

Consider a case if you do not use break statement:

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
  case 'A': document.write("Good job<br />");
  case 'B': document.write("Pretty good<br />");
  case 'C': document.write("Passed<br />");
  case 'D': document.write("Not so good<br />");
  case 'F': document.write("Failed<br />");
  default:  document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

This will produce following result:

Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block

To understand it in better way you can Try it yourself.

While writing a program, there may be a situation when you need to perform some action over and over again. In such situation you would need to write loop statements to reduce the number of lines.

JavaScript supports all the necessary loops to help you on all steps of programming.

The while Loop

The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.

Syntax:

while (expression){
   Statement(s) to be executed if expression is true
}

The purpose of a while loop is to execute a statement or code block repeatedly as long asexpression is true. Once expression becomes false, the loop will be exited.

Example:

Following example illustrates a basic while loop:

<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
while (count < 10){
  document.write("Current Count : " + count + "<br />");
  count++;
}
document.write("Loop stopped!");
//-->
</script>

This will produce following result:

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

To understand it in better way you can Try it yourself.

The do…while Loop:

The do…while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

Syntax:

do{
   Statement(s) to be executed;
} while (expression);

Note the semicolon used at the end of the do…while loop.

Example:

Let us write above example in terms of do…while loop.

<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
  document.write("Current Count : " + count + "<br />");
  count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>

This will produce following result:

Starting Loop
Current Count : 0
Loop stopped!

The for Loop

The for loop is the most compact form of looping and includes the following three important parts:

  • The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
  • The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.
  • The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by a semicolon.

Syntax:

for (initialization; test condition; iteration statement){
     Statement(s) to be executed if test condition is true
}

Example:

Following example illustrates a basic for loop:

<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
  document.write("Current Count : " + count );
  document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>

This will produce following result which is similar to while loop:

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!

There is one more loop supported by JavaScript. It is called for…in loop. This loop is used to loop through an object’s properties.

Because we have not discussed Objects yet, so you may not feel comfortable with this loop. But once you will have understanding on JavaScript objects then you will find this loop very useful.

Syntax:

for (variablename in object){
  statement or block to execute
}

In each iteration one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.

Example:

Here is the following example that prints out the properties of a Web browser’s Navigatorobject:

<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
  document.write(aProperty);
  document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>

This will produce following result:

Navigator Object Properties
appCodeName
appName
appMinorVersion
cpuClass
platform
plugins
opsProfile
userProfile
systemLanguage
userLanguage
appVersion
userAgent
onLine
cookieEnabled
mimeTypes
Exiting from the loop!

JavaScript provides you full control to handle your loops and switch statement. There may be a situation when you need to come out of a loop without reaching at its bottom. There may also be a situation when you want to skip a part of your code block and want to start next iteration of the look.

To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively.

The break Statement:

The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.

Example:

This example illustrates the use of a break statement with a while loop. Notice how the loop breaks out early once x reaches 5 and reaches to document.write(..) statement just below to closing curly brace:

<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
  if (x == 5){ 
     break;  // breaks out of loop completely
  }
  x = x + 1;
  document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

This will produce following result:

Entering the loop
2
3
4
5
Exiting the loop!

To understand it in better way you can Try it yourself.

We already have seen the usage of break statement inside a switch statement.

The continue Statement:

The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code block.

When a continue statement is encountered, program flow will move to the loop check expression immediately and if condition remain true then it start next iteration otherwise control comes out of the loop.

Example:

This example illustrates the use of a continue statement with a while loop. Notice how thecontinue statement is used to skip printing when the index held in variable x reaches 5:

<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
  x = x + 1;
  if (x == 5){ 
     continue;  // skill rest of the loop body
  }
  document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

This will produce following result:

Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!

To understand it in better way you can Try it yourself.

Using Labels to Control the Flow:

Starting from JavaScript 1.2, a label can be used with break and continue to control the flow more precisely.

label is simply an identifier followed by a colon that is applied to a statement or block of code. We will see two different examples to understand label with break and continue.

Note: Line breaks are not allowed between the continue or break statement and its label name. Also, there should not be any other statement in between a label name and associated loop.

Example 1:

<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop:   // This is the label name
for (var i = 0; i < 5; i++)
{
  document.write("Outerloop: " + i + "<br />");
  innerloop:
  for (var j = 0; j < 5; j++)
  {
     if (j >  3 ) break ;         // Quit the innermost loop
     if (i == 2) break innerloop; // Do the same thing
     if (i == 4) break outerloop; // Quit the outer loop
     document.write("Innerloop: " + j + "  <br />");
   }
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

This will produce following result:

Entering the loop!
Outerloop: 0
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 1
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 2
Outerloop: 3
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 4
Exiting the loop!

To understand it in better way you can Try it yourself.

Example 2:

<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop:   // This is the label name
for (var i = 0; i < 3; i++)
{
   document.write("Outerloop: " + i + "<br />");
   for (var j = 0; j < 5; j++)
   {
      if (j == 3){
         continue outerloop;
      }
      document.write("Innerloop: " + j + "<br />");
   } 
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

This will produce following result:

Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!

Functions in JavaScript
A function is a group of reusable code which can be called anywhere in your programme. This eliminates the need of writing same code again and again. This will help programmers to write modular code. You can divide your big programme in a number of small and manageable functions.

Like any other advance programming language, JavaScript also supports all the features necessary to write modular code using functions.

You must have seen functions like alert() and write() in previous chapters. We are using these function again and again but they have been written in core JavaScript only once.

JavaScript allows us to write our own functions as well. This section will explain you how to write your own functions in JavaScript.

Function Definition:

Before we use a function we need to define that function. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here:

<script type="text/javascript">
<!--
function functionname(parameter-list)
{
  statements
}
//-->
</script>

Example:

A simple function that takes no parameters called sayHello is defined here:

<script type="text/javascript">
<!--
function sayHello()
{
   alert("Hello there");
}
//-->
</script>

Calling a Function:

To invoke a function somewhere later in the script, you would simple need to write the name of that function as follows:

<script type="text/javascript">
<!--
sayHello();
//-->
</script>

To understand it in better way you can Try it yourself.

Function Parameters:

Till now we have seen function without a parameters. But there is a facility to pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters.

A function can take multiple parameters separated by comma.

Example:

Let us do a bit modification in our sayHello function. This time it will take two parameters:

<script type="text/javascript">
<!--
function sayHello(name, age)
{
   alert( name + " is " + age + " years old.");
}
//-->
</script>

Note: We are using + operator to concatenate string and number all together. JavaScript does not mind in adding numbers into strings.

Now we can call this function as follows:

<script type="text/javascript">
<!--
sayHello('Zara', 7 );
//-->
</script>

To understand it in better way you can Try it yourself.

The return Statement:

A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function.

For example you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program.

Example:

This function takes two parameters and concatenates them and return resultant in the calling program:

<script type="text/javascript">
<!--
function concatenate(first, last)
{
   var full;

   full = first + last;
   return  full;
}
//-->
</script>

Now we can call this function as follows:

<script type="text/javascript">
<!--
   var result;
   result = concatenate('Zara', 'Ali');
   alert(result );
//-->
</script>

To understand it in better way you can Try it yourself.

Advanced Concepts for Functions:

There is lot to learn about JavaScript functions. But I have put following important concepts in this tutorial. If you are not in furry then I would suggest to go through them at least once.

_________________________________________________________________________

What is an Event ?

JavaScript’s interaction with HTML is handled through events that occur when the user or browser manipulates a page.

When the page loads, that is an event. When the user clicks a button, that click, too, is an event. Another example of events are like pressing any key, closing window, resizing window etc.

Developers can use these events to execute JavaScript coded responses, which cause buttons to close windows, messages to be displayed to users, data to be validated, and virtually any other type of response imaginable to occur.

Events are a part of the Document Object Model (DOM) Level 3 and every HTML element have a certain set of events which can trigger JavaScript Code.

Please go through this small tutorial for a better understanding HTML Event Reference. Here we will see few examples to understand a relation between Event and JavaScript:

onclick Event Type:

This is the most frequently used event type which occurs when a user clicks mouse left button. You can put your validation, warning etc against this event type.

Example:

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

This will produce following result and when you click Hello button then onclick event will occur which will trigger sayHello() function.

To understand it in better way you can Try it yourself.

onsubmit event type:

Another most important event type is onsubmit. This event occurs when you try to submit a form. So you can put your form validation against this event type.

Here is simple example showing its usage. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true the form will be submitted otherwise it will not submit the data.

Example:

<html>
<head>
<script type="text/javascript">
<!--
function validation() {
   all validation goes here
   .........
   return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>

onmouseover and onmouseout:

These two event types will help you to create nice effects with images or even with text as well. The onmouseover event occurs when you bring your mouse over any element and theonmouseout occurs when you take your mouse out from that element.

Example:

Following example shows how a division reacts when we bring our mouse in that division:

<html>
<head>
<script type="text/javascript">
<!--
function over() {
   alert("Mouse Over");
}
function out() {
   alert("Mouse Out");
}
//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

What is page redirection ?

When you click a URL to reach to a page X but internally you are directed to another page Y that simply happens because of page re-direction. This concept is different from JavaScript Page Refresh.

There could be various reasons why you would like to redirect from original page. I’m listing down few of the reasons:

  • You did not like the name of your domain and you are moving to a new one. Same time you want to direct your all visitors to new site. In such case you can maintain your old domain but put a single page with a page re-direction so that your all old domain visitors can come to your new domain.
  • You have build-up various pages based on browser versions or their names or may be based on different countries, then instead of using your server side page redirection you can use client side page redirection to land your users on appropriate page.
  • The Search Engines may have already indexed your pages. But while moving to another domain then you would not like to lose your visitors coming through search engines. So you can use client side page redirection. But keep in mind this should not be done to make search engine a fool otherwise this could get your web site banned.

How Page Re-direction works ?

Example 1:

This is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows:

<head>
<script type="text/javascript">
<!--
   window.location="http://www.newlocation.com";
//-->
</script>
</head>

To understand it in better way you can Try it yourself.

Example 2:

You can show an appropriate message to your site visitors before redirecting them to a new page. This would need a bit time delay to load a new page. Following is the simple example to implement the same:

<head>
<script type="text/javascript">
<!--
function Redirect()
{
    window.location="http://www.newlocation.com";
}

document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>

Here setTimeout() is a built-in JavaScript function which can be used to execute another function after a given time interval.

To understand it in better way you can Try it yourself.

Example 3:

Following is the example to redirect site visitors on different pages based on their browsers :

<head>
<script type="text/javascript">
<!--
var browsername=navigator.appName; 
if( browsername == "Netscape" )
{ 
   window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
   window.location="http://www.location.com/ie.htm";
}
else
{
  window.location="http://www.location.com/other.htm";
}
//-->
</script>
</head>

JavaScript Dialog Boxes
JavaScript supports three important types of dialog boxes. These dialog boxes can be used to raise and alert, or to get confirmation on any input or to have a kind of input from the users.

Here we will see each dialog box one by one:

Alert Dialog Box:

An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some text but user does not enter that field then as a part of validation you can use alert box to give warning message as follows:

<head>
<script type="text/javascript">
<!--
   alert("Warning Message");
//-->
</script>
</head>

Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button “OK” to select and proceed.

To understand it in better way you can Try it yourself.

Confirmation Dialog Box:

A confirmation dialog box is mostly used to take user’s consent on any option. It displays a dialog box with two buttons: OK and Cancel.

If the user clicks on OK button the window method confirm() will return true. If the user clicks on the Cancel button confirm() returns false. You can use confirmation dialog box as follows:

<head>
<script type="text/javascript">
<!--
   var retVal = confirm("Do you want to continue ?");
   if( retVal == true ){
      alert("User wants to continue!");
	  return true;
   }else{
      alert("User does not want to continue!");
	  return false;
   }
//-->
</script>
</head>

To understand it in better way you can Try it yourself.

Prompt Dialog Box:

The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enable you to interact with the user. The user needs to fill in the field and then click OK.

This dialog box is displayed using a method called prompt() which takes two parameters (i) A label which you want to display in the text box (ii) A default string to display in the text box.

This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window method prompt() will return entered value from the text box. If the user clicks on the Cancel button the window method prompt() returns null.

You can use prompt dialog box as follows:

<head>
<script type="text/javascript">
<!--
   var retVal = prompt("Enter your name : ", "your name here");
   alert("You have entered : " +  retVal );
//-->
</script>
</head>

Java Script Animation

You can use JavaScript to create a complex animation which includes but not limited to:

  • Fireworks
  • Fade Effect
  • Roll-in or Roll-out
  • Page-in or Page-out
  • Object movements

You might be interested in existing JavaScript based animation library : Script.Aculo.us.

This tutorial will give you basic understanding on how to use JavaScript to create an animation.

JavaScript can be used to move a number of DOM elements (<img />, <div> or any other HTML element) around the page according to some sort of pattern determined by a logical equation or function.

JavaScript provides following two functions to be frequently used in animation programs.

  • setTimeout( function, duration) – This function calls function after durationmilliseconds from now.
  • setInterval(function, duration) – This function calls function after every durationmilliseconds.
  • clearTimeout(setTimeout_variable) – This function calls clears any timer set by the setTimeout() functions.

JavaScript can also set a number of attributes of a DOM object including its position on the screen. You can set top and left attribute of an object to position it anywhere on the screen. Here is the simple syntax:

// Set distance from left edge of the screen.
object.style.left = distance in pixels or points; 

or
// Set distance from top edge of the screen.
object.style.top = distance in pixels or points;

Manual Animation:

So let’s implement one simple animation using DOM object properties and JavaScript functions as follows:

<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
function init(){
   imgObj = document.getElementById('myImage');
   imgObj.style.position= 'relative'; 
   imgObj.style.left = '0px'; 
}
function moveRight(){
   imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click button below to move the image to right</p>
<input type="button" value="Click Me" onclick="moveRight();" />
</form>
</body>
</html>

Here is the explanation of the above example:

  • We are using JavaScript function getElementById() to get a DOM object and then assigning it to a global variable imgObj.
  • We have defined an initialization function init() to initialize imgObj where we have set itsposition and left attributes.
  • We are calling initialization function at the time of window load.
  • Finally, we are calling moveRight() function to increase left distance by 10 pixels. You could also set it to a negative value to move it to the left side.

To understand it in better way you can Try it yourself.

Automated Animation:

In the above example we have seen , how an image moves to right with every click. We can automate this process by using JavaScript function setTimeout() as follows:

<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
   imgObj = document.getElementById('myImage');
   imgObj.style.position= 'relative'; 
   imgObj.style.left = '0px'; 
}
function moveRight(){
   imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
   animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
   clearTimeout(animate);
   imgObj.style.left = '0px'; 
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
</body>
</html>

Here we have add more spice. So let’s see what is new here:

  • The moveRight() function is calling setTimeout() function to set the position of imgObj.
  • We have added a new function stop() to clear the timer set by setTimeout() function and to set the object at its initial position.

To understand it in better way you can Try it yourself.

Rollover with a Mouse Event:

Here is a simple example showing image rollover with a mouse events:

<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type="text/javascript">
<!--
if(document.images){
    var image1 = new Image();      // Preload an image
    image1.src = "/images/html.gif";
    var image2 = new Image();      // Preload second image
    image2.src = "/images/http.gif";
}
//-->
</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p>
<a href="#" onMouseOver="document.myImage.src=image2.src;"
            onMouseOut="document.myImage.src=image1.src;">
<img name="myImage" src="/images/html.gif" />
</a>
</body>
</html>

Let’s see what is different here:

  • At the time of loading this page, the if statement checks for the existence of the image object. If the image object is unavailable, this block will not be executed.
  • The Image() constructor creates and preloads a new image object called image1.
  • The src property is assigned the name of the external image file called /images/html.gif.
  • Similar way we have created image2 object and assigned /images/http.gif in this object.
  • The # (hash mark) disables the link so that the browser does not try to go to a URL when clicked. This link is an image.
  • The onMouseOver event handler is triggered when the user’s mouse moves onto the link, and the onMouseOut event handler is triggered when the user’s mouse moves away from the link (image).
  • When the mouse moves over the image, the HTTP image changes from the first image to the second one. When the mouse is moved away from the image, the original image is displayed.
  • When the mouse is moved away from the link, the initial image html.gif will reappear on the screen.

_________________________________________________________________________

Below are some of the Samples of Java Script

In this article, you’ll find some commonly used snippets of JavaScript and HTML code that you can use when implementing sites hosted on this service.

 

Please note that the following code samples are provided as a guide only; the code may require customization to work with your site. You must be proficient in JavaScript implementation, because support is not provided for the implementation of these items.

 

When inserting JavaScript on your page, make sure to paste the sample code at the end of your HTML document to ensure all page elements are rendered before the script is run. Otherwise, the scripts may cause errors. Always keep track of the most recent working backup copy of the page, so that you can revert to the archived version if you add code that does not work on a page.

 

To learn more about rolling back to a previous iteration of an archived page, see Understanding web pages.

Set the value of the username field equal to the email address field

 

To make the visitor’s email address their Secure Zone username, you’ll need to edit the code in the web form. In this system, the username and the email address fields are different, and can contain different values by default. In order for the registered visitor to use their email address to login, their email address must also be stored in the Username field.

 

To customize a web form to automatically populate the username field with the visitor’s email address, follow these steps:

Insert the web form on to a web page.

Use CSS styles to hide (not remove) the Username field. You can do this by wrapping it in a HTML div element which is set to hidden. The code to hide the Username field is provided below:

 

<div style= display:none;>Username<br><input type=text name=”Username” ></div>

Add the following code to make the email address field automatically update the Username field when an email address is entered.

<input type=text name=”EmailAddress” onBlur=”document.getElementById(‘Username’).value=this.value;>

Hiding the “Shopping Cart Is Empty” message

 

To avoid the default message regarding the shopping cart’s status, add this JavaScript to hide the catCartSummary from view:

<script type=”text/javascript”>

if (document.cookie && document.cookie.indexOf(“CartID”) < 1) {

document.getElementById(‘catCartSummary’).style.display = “none”;

}

</script>

Assigning a Web App item name to a page title

 

You can set the system created pages that display when drilling down to individual Web App items to display as the page’s title, to make the site easier to navigate. Add the following code:

<script type=”text/javascript”>

function titlechange()

{

document.title = “{tag_item_name}”;

}

</script>

</head>

<body onload=”titlechange()”>

Redirecting to another page

 

The following JavaScript code example redirects a visitor to various URLs of the same site to different web pages.

<script type=”text/javascript”>

 

var url = document.location.href.toLowerCase();

if (url.indexOf(‘domain1.com’) != -1)

document.location = ‘http://domain1.com/index1.htm&#8217;;

if (url.indexOf(‘domain2.com’) != -1)

document.location = ‘http://domain2.com/index2.htm&#8217;;

 

</script>

Logging into different Secure Zones according to ID number

 

You can add a menu with options that enable you to select the corresponding ID number, using some basic HTML code:

<select id=”selectZone”>

<option value=”154″>Customer</option>

<option value=”150″>Staff Intranet</option>

<option value=”152″>Kanfa Aragon</option>

<option value=”168″>Technip</option>

<option value=”347″>Heron</option>

</select>

 

And then, add this JavaScript to the end of the same login page:

<script language=”javascript”>

 

function checkWholeForm43650(theForm){

var why = “”;

 

if (theForm.Username) why += isEmpty(theForm.Username.value, “Username”);

if (theForm.Password) why += isEmpty(theForm.Password.value, “Password”);

if (why != “”){

alert(why);

return false;

}

 

var sel = document.getElementById(“selectZone”);

theForm.action = ‘/ZoneProcess.aspx?ZoneID=’+sel.options[sel.selectedIndex].value+’&OID={module_oid}&OTYPE={module_otype}’;

theForm.submit();

return false;

}

 

</script>

 

 

 

 

 

 

 

Setting the billing information to be the same as the shipping information

 

This script will populate the billing information in the checkout form if the customer selects the “Same as shipping” checkbox.

 

Add this code to the checkbox:

<input type=”checkbox” onclick=”SetBilling(this.checked);”/> Same as Shipping

 

And then, at the bottom of the page, add the following JavaScript function:

<script type=”text/javascript”>

function SetBilling(checked) {

if (checked) {

document.getElementById(‘BillingAddress’).value = document.getElementById(‘ShippingAddress’).value;

document.getElementById(‘BillingCity’).value = document.getElementById(‘ShippingCity’).value;

document.getElementById(‘BillingState’).value = document.getElementById(‘ShippingState’).value;

document.getElementById(‘BillingZip’).value = document.getElementById(‘ShippingZip’).value;

document.getElementById(‘BillingCountry’).value = document.getElementById(‘ShippingCountry’).value;

} else {

document.getElementById(‘BillingAddress’).value = ”;

document.getElementById(‘BillingCity’).value = ”;

document.getElementById(‘BillingState’).value = ”;

document.getElementById(‘BillingZip’).value = ”;

document.getElementById(‘BillingCountry’).value = ”;

}

}

</script>

Adding an email verification field to a web form

 

You can update a web form to require that visitors enter their email address twice, to verify it. This is similar to password verification, because the logic added to the form compares both fields to ensure they match. Open the the page the web form is and paste the following code just below the email address field:

<input id=”EmailAddress2″ class=”cat_textbox” name=”EmailAddress2″ maxlength=”255″/>

 

Then you can embed the following JavaScript code into the existing JavaScript code of the web form:

if (document.getElementById(‘EmailAddress’).value !=document.getElementById(‘EmailAddress2’).value)

{

alert(‘- Email address and its confirmation do not match\n’);

return false;

}

 

The existing code looks something like this (although in your code the function name will be different):

<script type=”text/javascript”>

var submitcount77199 = 0;

function checkWholeForm77199(theForm)

{var why = “”;if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, “First Name”);

if (theForm.LastName) why += isEmpty(theForm.LastName.value, “Last Name”);

if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);

if (!theForm.PaymentMethodType || getRadioSelected(theForm.PaymentMethodType) == 1)

{ if (theForm.CardName) why += isEmpty(theForm.CardName.value, “Name on Card”);

if (theForm.CardNumber) why += isNumeric(theForm.CardNumber.value, “Card Number”);

if (theForm.Amount) why += isCurrency(theForm.Amount.value, “Amount”); }

if (theForm.PaymentMethodType) why += checkSelected(theForm.PaymentMethodType, “Payment Method”);

if(why != “”){alert(why);return false;}if(submitcount77199 == 0)

{submitcount77199++;theForm.submit();return false;}

else{alert(“Form submission is in progress.”);return false;}}

</script>

 

After you add the new JavaScript code to the existing code, it will look something like this:

<script type=”text/javascript”>

var submitcount77199 = 0;

function checkWholeForm77199(theForm)

{var why = “”;if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, “First Name”);

if (theForm.LastName) why += isEmpty(theForm.LastName.value, “Last Name”);

if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);

if (!theForm.PaymentMethodType || getRadioSelected(theForm.PaymentMethodType) == 1)

{ if (theForm.CardName) why += isEmpty(theForm.CardName.value, “Name on Card”);

if (theForm.CardNumber) why += isNumeric(theForm.CardNumber.value, “Card Number”);

if (theForm.Amount) why += isCurrency(theForm.Amount.value, “Amount”); }

if (theForm.PaymentMethodType) why += checkSelected(theForm.PaymentMethodType, “Payment Method”);

if (document.getElementById(‘EmailAddress’).value != document.getElementById(‘EmailAddress2’).value)

{

alert(‘- Email address and its confirmation do not match\n’);

return false;

}

if(why != “”){alert(why);return false;}if(submitcount77199 == 0)

{submitcount77199++;theForm.submit();return false;}

else{alert(“Form submission is in progress.”);return false;}}

</script>

Hiding a retail price for items that are not on sale

 

Add the following script to the large or small products layout for an online store:

<script language=”javascript”><!–

 

 

var onsale_{tag_productid} = “{tag_onsale}”;

 

if (onsale_{tag_productid} == “0”) {

document.getElementById(“rrpprice_{tag_productid}”).style.display = ‘none’; }

 

 

//–></script>

 

Then you would assign the following tag ID to a retail price tag

<div id=”rrpprice_{tag_productid}”>{tag_retailprice}</div>

 

After adding this script, the retail price will be hidden for every item that is not currently on sale.

Creating a dropdown menu for multi-currency websites

 

Add this script to enable customers to choose from a list of supported currencies for an online store:

Please select Country: <select id=”selectCountry” onchange=”document.location=this.options[this.selectedIndex].value;”>

<option value=”http://www.yourURL.com/CatalogueRetrieve.aspx?CatalogueID=15789″>Australia</option&gt;

<option value=”http://nz.yourURL.com/CatalogueRetrieve.aspx?CatalogueID=15789″>New Zealand</option>

<option value=”http://uk.yourURL.com/CatalogueRetrieve.aspx?CatalogueID=15789″>United Kingdom</option>

</select>

 

//THE ABOVE CODE WILL PROVIDE YOU WITH A DROPDOWN THAT WILL SIMPLY REFRESH THE PAGE. THERE ARE MORE ELEGANT WAYS TO DO THIS!

 

<script type=”text/javascript”>

var country = document.location.host;

var sel =document.getElementById(‘selectCountry’);

if (country == ‘nz.yourURL’ ){

sel.selectedIndex = 1;

}

else if (country == ‘uk.yourURL’ ){

sel.selectedIndex = 2;

}

else{

sel.selectedIndex = 0;

}

</script>

 

// THIS CODE WILL SELECT THE CORRECT DROPDOWN OPTION ACCORDING TO THE URL

 

Returning a customer to a default URL after viewing the receipt page

 

After a customer has made a purchase, if they continue browsing the site, the pages will be using the site’s secure URL. If you want to redirect customers to a default URL, place the following script in your Receipt (Buy) online shop layout:

<script>

var siteUrl = ‘http://www.yoursite.com&#8217;;

var links = document.getElementsByTagName(‘A’);

 

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

{

if (links[i].getAttribute(‘href’))

{

var href = links[i].getAttribute(‘href’);

if (href.substring(0,4) != ‘http’ && href.substring(0,1) == ‘/’)

{

//this example requires your links to have absolute paths.

//document-relative paths and absolute URLs are not supported.

links[i].setAttribute(‘href’, siteUrl + href);

}

}

}

 

</script>

Returning a customer to a different URL based on their country selection

 

If your online store uses several domains with different currencies, you can modify the script above to support the different transactions. Just replace this line:

var siteUrl = ‘http://www.yoursite.com&#8217;;

 

with this code:

var siteUrl = ‘http://www.yoursite.com&#8217;; //the default in case we don’t match a country

 

if (‘{module_visitorcountrycode}’ == ‘AU’) siteUrl = ‘http://www.yoursite.com.au&#8217;;

if (‘{module_visitorcountrycode}’ == ‘NZ’) siteUrl = ‘http://www.yoursite.co.nz&#8217;;

Showing the contents of a hidden div tag if a registered visitor is logged in

 

Sometimes it is helpful to initially hide an element, and then check to see if the visitor is logged in. If the visitor is logged in, you can add logic to display that hidden element. In this case, you can use the {module_isloggedin} module that displays a value of 1 if customer is logged in and 0 if they are not logged in. Add the following code to hide the div container and its contents:

<div id=”hiddenform” style=”display:none”>

 

 

</div>

 

And this is the script used to display the div container if the visitor is logged in:

var loggedin = “{module_isloggedin}”;

if  (loggedin == 1)

document.getElementById(‘hiddenform’).style.display = “block”;

Replacing Shipping options with custom text

 

You can update the shopping cart to add a custom message next to the shipping options, using the code below:

<script type=”text/javascript”>

var sel = document.getElementById(‘ShippingOptions’)

for(var i=sel.options.length-1;i>=0;i–)

{

if(sel.options[i].value == “-1”)

sel.options[i].text = “Here goes the text of whatever you want to replace Choose Shipping Options to”;

}

</script>

 

 

Pre-Loading images using Javascript

 

If your site includes larger file sizes, you can help improve the visitor’s experience by pre-loading them before they are requested. That will reduce the latency that may occur as the larger file downloads. Add this code:

<script language=”javascript”>

var home = new Image();

home src=”http://yourdomain.com/image.jpg&#8221;

 

var home-roll = new Image();

home src=”http://yourdomain.com/image.jpg&#8221;

 

</script>

 

 

 

Auto-Selecting one Shipping Option

 

To auto-select a a shipping option, add the Javascript shown below to the Shopping Cart Layout:

<script type=”text/javascript”>

var shippingOptions = document.getElementById(‘ShippingOptions’);

if (shippingOptions) {

shippingOptions.selectedIndex = 1;

shippingOptions.onchange();

}

</script>

 

Supressing alert windows

 

Use the following code with caution and be mindful where you place it, because it will supress any alert windows. For example, if you place it on a site-wide template, it will supress any alert pop-up window, which may impact the features of your site.

 

<script type=”text/javascript”>

window.alert=function(msg){}

</script>

 

Overriding the Checkout button on the Checkout page

 

If you’d like to override the default checkout button, add the following script to the Checkout Step layout. You can access this layout file by choosing Admin >More Customization Options. Click the Online Shop Layouts icon. In the list that appears, select the  Checkout Step layout.

 

This script essentially allows you to add a JavaScript function before the checkout submits and the system presents the registration step.

<script type=”text/javascript”>

function AddEvent(func){

var btn = document.getElementById(‘catshopbuy’);

var oldonclick = btn.onclick;

if (typeof btn.onclick != ‘function’){

btn.onclick = func;

}

else{

btn.onclick = function() {

func();

return oldonclick();

};

}

}

 

function func(){

alert(‘hi’);

}

 

AddEvent(func);

 

</script>

 

Changing the message: This product is unavailable or out of stock.

 

To change the message that’s displayed when the last unit of a product has been added to a cart, (in other words, when the system detects that the item is out of stock), you can change the message the system displays: This product is unavailable or out of stock.

 

To do this, add the following JavaScript code to a site-wide template or to the online store’s Overall layout. To access the Overall layout, choose Admin > More Customization Options, and then choose the Online Shop Layouts icon.

<script type=”text/javascript”>

function AddProductExtras(catalogId,productId,ret) {

var td = document.getElementById(‘catProdTd_’+productId);

if (td.innerHTML == ‘This product is unavailable or out of stock.’)

td.innerHTML = ‘Product added successfully.’;

}

</script>

 

 

 

Clearing the values of form fields when a visitor browses back to a previously submitted form

 

Implement the following script to make your site more secure. For example, add this code to ensure that a visitor’s entries into a web form are not ‘viewable’ by navigating ‘back’ to the page after the form’s submission. Place the following code on the page with the web form.

<script type=”text/javascript”>

var ele = document.getElementsByTagName(‘input’);

var len = ele.length;

for(var i=0;i<len;i++){

if(ele[i].type == ‘text’)

ele[i].value=”;

}

</script>

 

Changing the date format to North American date format

Announcement dates

 

When using the Announcements module, you can use {tag_counter} to generate the item ID and to access the date. Then, you can use some JavaScript to re-format the date.

 

In this example, this tag {tag_eventfromdate} is reformatted, but you can use the same method for any date tag. Here is the HTML code you need to use in your announcement layout. Note that the important part is id=”date{tag_counter}”.

 

You’ll add this code in the List layout. In the Detailed layout, just change the id from id=”date{tag_counter} to something else, such as id=”dateid”.

<span id=”date{tag_counter}”>{tag_eventfromdate}</span>

 

The JavaScript below converts the default date format (23-Apr-2009) into a North American date format: Apr/23/2009.

<script type=”text/javascript”>

var originalDate = document.getElementById(‘date{tag_counter}’).innerHTML;

var dateBits = originalDate.split(“-“);

document.write(dateBits[1] + “/” + dateBits[0] + “/” + dateBits[2]);

</script>

 

 

 

 

Note: You can feed the date directly into the var originalDate like this:

 

var originalDate = “{tag_eventfromdate}”;

Literature dates

 

Similar to Announcements, you can update Literature items by using {tag_counter} to generate the item ID and access the date. Then use some JavaScript to re-format the date.

 

In the example below, the tag {tag_expirydate} is reformatted. However, keep in mind that you can use the same method for any date tag. Here is the HTML code you need to use in your announcement layout. Note that the important part of the code is: id=”date{tag_counter}”.

 

Add this code to the List layout. In the Detailed layout, simply change the id from id=”date{tag_counter} to something else, such as id=”dateid”.

<span id=”date{tag_counter}”>{tag_expirydate}</span>

 

The following JavaScript code will take the date formatted like this: 23-Apr-2009 and convert it to a North American date format, like this: Apr/23/2009.

<script type=”text/javascript”>

var originalDate = document.getElementById(‘date{tag_counter}’).innerHTML;

var dateBits = originalDate.split(“-“);

document.write(dateBits[1] + “/” + dateBits[0] + “/” + dateBits[2]);

</script>

 

Note: You can feed the date directly into var originalDate, like this var originalDate = “{tag_expirydate}”;

Refreshing the page after adding a product to a cart

 

Add this code in the Site-Wide Template that your shopping cart is using (or link to this JavaScript in an external .js file).

<script type=”text/javascript”>

function AddProductExtras(){

document.location.reload(true);

}

</script>

Hiding the red X displayed by Internet Explorer when you have empty image fields in a Web App

 

In the template or web page, place the following JavaScript in the <head> of the page.

<script language=”JavaScript”>

function ImageLoadFailed() {

window.event.srcElement.style.display = “None”;

}

</script>

 

Then, in the Web App layout where you the image is displayed, place the following:

<img src=”{tag_imagename_value}?Action=thumbnail&Width=80&Height=80″

OnError=”ImageLoadFailed()” class=”right” alt=”{tag_name_nolink}” />

 

 

 

Capturing form fields in the special instructions box for a product

 

Place this code on the large product layout. You can access it by choosing Admin > More Customization Options. Then click the Online Shop Layouts. In the list that appears, click the Large Product Layout.

 

This special instructions text field will take three separate input lines of text and combine them into one set of special instructions, separated by commas, assuming that the product has the Capture Details option enabled.

 

Then, you can add the item to the cart when selecting the image. In the code below, you’ll need to substitute a correct path for src=”/yourcustomisedbutton.jpg” in the third line from the bottom of this code snippet.

<html>

<head>

<script language=”javascript”>

<!–

function CollectText(){

var gettxt1,gettxt2,gettxt3;

gettxt1=document.getElementById(“txt1”).value;gettxt2=document.getElementById(“txt2”).value;gettxt3=document.getElementById(“txt3″).value;

if(gettxt1==”” && gettxt2==”” && gettxt3==””){

CombinedVal=””;

} else {

CombinedVal= gettxt1 + ” , ” + gettxt2 + ” , ” + gettxt3;

}

document.getElementById(“catProdInstructions_{tag_productid}”).value=CombinedVal;

}

–>

</script>

</head>

<body>

<form>

Forrm Fields (for form on which you wish to capture test in separate lines)

<br />

Line 1:<br />

<input type=”text” id=”txt1″ name=”txt1″ /><br />

Line 2:<br />

<input type=”text” id=”txt2″ name=”txt2″ /><br />

Line 3:<br />

<input type=”text” id=”txt3″ name=”txt3″ /><br />

</form>

{tag_capturedetails}

<a href=”#”><img alt=”” src=”/yourcustomisedbutton.jpg” onclick=”CollectText(); AddToCart({tag_catalogueid},{tag_productid},”,1,false);return false;” /></a>

</body>

</html>

 

 

Capturing the visitor’s name and phone number only

 

In this example, the webform validation JavaScript was altered to capture the full name and the cell phone only. The JavaScript below will actually take the cell phone number from the cell number field, attach “@email.com” to it and populate the email field with this value. This must be done programmatically, because the form cannot be submitted without a valid email address.

 

Add the following line to the existing script:

document.getElementById(‘EmailAddress’).value = document.getElementById(‘CellPhone’).value + ‘@email.com’;

 

You should also disable the auto responder by adding &SAR=False to the action URL and redirecting the visitor to a custom page by appending &PageID=/landingpage.htm to it.

 

Here’s an example of the form code:

<form name=”catwebformform63295″ method=”post” onsubmit=”return checkWholeForm63295(this)” enctype=”multipart/form-data” action=”/FormProcessv2.aspx?WebFormID=19401&OID={module_oid}&OTYPE={module_otype}&EID={module_eid}&CID={module_cid}&SAR=False&PageID=/landingpage.htm”>

<span class=”req”>*</span>  Required

<table cellspacing=”0″ cellpadding=”2″ border=”0″ class=”webform”>

<tbody>

<tr>

<td><label for=”FirstName”>First Name <span class=”req”>*</span></label><br />

<input type=”text” name=”FirstName” id=”FullName” class=”cat_textbox” maxlength=”255″ /></td>

</tr>

<tr>

<td style=”display: none;”><label for=”EmailAddress”>Email Address <span class=”req”>*</span></label><br />

<input type=”text” name=”EmailAddress” id=”EmailAddress” class=”cat_textbox” maxlength=”255″ /></td>

</tr>

<tr>

<td><label for=”CellPhone”>Cell Phone Number <span class=”req”>*</span></label><br />

<input type=”text” name=”CellPhone” id=”CellPhone” class=”cat_textbox” maxlength=”255″ /></td>

</tr>

<tr>

<td><input type=”submit” value=”Submit” id=”catwebformbutton” /></td>

</tr>

</tbody>

</table>

<script src=”/CatalystScripts/ValidationFunctions.js” type=”text/javascript”></script>

<script type=”text/javascript”>

var submitcount63295 = 0;

function checkWholeForm63295(theForm){

var why = “”;

document.getElementById(‘EmailAddress’).value = document.getElementById(‘CellPhone’).value + ‘@email.com’;

if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, “First Name”);if (theForm.LastName) why += isEmpty(theForm.LastName.value, “Last Name”);

if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value); if (theForm.CellPhone) why += isEmpty(theForm.CellPhone.value, “Cell Phone Number”);

if(why != “”){alert(why);return false;}if(submitcount63295 == 0){submitcount63295++;theForm.submit();return false;}

else{alert(“Form submission is in progress.”);return false;}}</script>

</form>

<br />

 

Date Picker Using jsDatePick

jsDatePick is a javascript date picker that uses DOM techniques to generate its HTML code. Read the parameters and working examples below, and within minutes, you can have a popup date picking solution on your website.

Read below for full documentation of parameters, and to download jsDatePick. We developed jsDatePick as a custom date picking module for our web-based money management software – check it out if you like.

Download.

Link Back.

<a href=”http://javascriptcalendar.org&#8221; />Javascript Calendar</a>

Spread the Word.

jsDatePick – All Parameters

  • useMode (Integer) – Possible values are 1 and 2 as follows:
    • 1 – The calendar’s HTML will be directly appended to the field supplied by target
    • 2 – The calendar will appear as a popup when the field with the id supplied in target is clicked.
  • target (String) – The id of the field to attach the calendar to , usually a text input field when using useMode 2.
  • isStripped (Boolean) – When set to true the calendar appears without the visual design – usually used with useMode 1
  • selectedDate (Object) – When supplied , this object tells the calendar to open up with this date selected already.
  • yearsRange (Array) – When supplied , this array sets the limits for the years enabled in the calendar.
  • limitToToday (Boolean) – Enables you to limit the possible picking days to today’s date.
  • cellColorScheme (String) – Enables you to swap the colors of the date’s cells from a wide range of colors.
    Available color schemes:

    • aqua
    • armygreen
    • bananasplit
    • beige
    • deepblue
    • greenish
    • lightgreen
    • ocean_blue – If you choose not to supply the cellColorScheme variable – the calendar will default to this color.
    • orange
    • peppermint
    • pink
    • purple
    • torqoise

Calendar Date Picking Examples

1. Simple Javascript Date Picking Calendar

This is an example of the JsDatePick calendar in action with an input field – The user launches the calendar by entering the input field, and then chooses a date, automatically returning the selected date to the field. This is the most basic use of a javascript calendar.

new JsDatePick({
	useMode:2,
	target:"aFieldId"
});

2. Full configuration detailed

jsDatePick has a range of parameters for extending or limiting default functionality. See the full parameter list above for a complete list. The following statement shows exactly what is possible.

    new JsDatePick({
        useMode:2,
        target:"aFieldId",        
        isStripped:false,
        selectedDate:{
            year:2009,
            month:4,
            day:16
       	},
        yearsRange: new Array(1971,2100),
        limitToToday:true,
    });

3. HTML Direct Appending Example

This is an HTML direct-appending example of the JsDatePick calendar. When used with this method, it’s recommended to keep the reference to the Javascript object in order to retrieve the selected date later on when the calendar is clicked. This is done by setting a function to the predefined onSelected event handler, using the method JsDatePick.setOnSelectedDelegate (function(){ alert(“a date has been chosen!”); });

    g_calendarObject = new JsDatePick({
        useMode:1,
        isStripped:true,
        target:"aFieldId",
	  cellColorScheme:"armygreen"
    });

    g_calendarObject.setOnSelectedDelegate(function(){
        var obj = g_calendarObject.getSelectedDay();

        alert("a date was just selected and the date is : " + obj.day + "/" + obj.month + "/" + obj.year);
    });

Does your website need an interactive event calendar?

Why another JavaScript Calendar…

  • a good-looking, if not the best, javascript calendar or datepicker without the pain of javascript.
  • simple to start with, while powerful enough to meet any sophisticated requirement, even driven by XML.
  • all-purpose and extremely perfect for plain HTML, ASP, ASP.Net, JSP, PHP, ColdFusion etc.

Wouldn’t it be terrific if your visitors could see what you have planned by date for the entire month(s)? Do you love to see something intuitive on your website like the calendar on the left column of this page?

You may love it, but also hesitate about the browser compatibility and the complexity of scripts. Luckily, such feelings are history now – just take a look by right-click this page and select “view source” – you’ll be amazed to find out that the calendar on the left side of this page is rendered by just a standard HTML tag. Wasn’t it a dream of every web developer to have a calendar tag supported by all the browsers? It has now come true, right before your eyes.

Above is the HTML tag for the calendar on the left side. It not only works in IE, but also in other major browsers such as Netscape, Mozilla, Safari and Opera etc. And it not just looks simple, it actually is that simple. You can put it anywhere in your web page, in tables/layers/menus, just the same way as the other HTML tags. And not just one, you can have many of them synchonized to behave like an integrated unit. Please take a look at our online demos or even download a free version to play locally. You’ll see why we call it eXtremely Perfect.

Working with CalendarXP’s calendar and date picker products, there is almost nothing messy in your webpage. Although it’s a javascript solution it’s designed so well that you don’t even have to know anything about javascript in order to use it. All you need is to place the calendar tag to wherever you want it to appear. And there are plenty examples and variety themes in the download package that may inspire the design of your website.

As a mature product, almost every single bit of the CalendarXP product can be customized to suit your own unique taste. Although the product itself doesn’t rely on server-side scripts, it surely can benefit from them at your wish. It supports various web technology, including ASP.net, JSP, PHP, ColdFusion and XML. Please go over our detailed tutorials and you will find how powerful the javascript calendar can be. Following please find a sample snippet of the calendar agenda in XML:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<agenda> 
  <event year="2005" month="4" date="1" bgcolor="#00ff00"
fgcolor="black" bgimg="" border="gold"> 
    <tooltip>this is a test</tooltip> 
    <action>alert(123)</action> 
  </event> 
  <event year="2005" month="1" date="1" bgcolor="green"
border="null"> 
    <tooltip>this is a new test</tooltip> 
    <action/> 
    <html><![CDATA[ 
<br> 
<b>this is a new test</b> 
    ]]></html> 
  </event> 
</agenda>

Another feature worth mentioning is that the CalendarXP was designed from scratch to house and display all kinds of daily events, which made it outstanding from the other javascript calendar you may find on the internet. It includes advanced features such as displaying events in every weekday of the month, multiple events in any date and even recurring events, e.g. Easter holidays. The events are stored in a seperate, simple javascript file. You may edit the agenda file and upload it to your web host. Alternatively you could choose to dynamically generate the agenda file from your backend database. You may also include HTML code in the event text so as to display images or links.

You should never be bound to plain layouts, boring colors and sluggish interface. You deserve better – and CalendarXP gives you the choice of making it better, in your own way. Simply use our theme gallery as a lead-in to your fantastic creativity and download the product to unleash the potential of your website, NOW!

 References of Most Rated Links from which the source and information can be copied
POP UP WINDOW

JavaScript Popup Windows

in JAVASCRIPT POPUP WINDOWS

JavaScript popups are handy to display help information or to zoom in an Image.

There are different types of Popups. The first type is a new browser window opened using the window.open() function. Such types of Popup windows were overused and exploited by many websites during the earlier days of the web. This resulted in the later versions of browsers blocking popup windows. Eventually, popup windows became almost extinct now. Automatically opening popup windows is considered a very bad practice.

Div based popups

Div is a block of content enclosed with the <div> and </div> tags. Unlike the browser window popups, div based popups are less intrusive and are often very useful.

There are a number of ways to use a popup.

Tooltips

JavScript tooltip

Tooltips are useful pieces of information displayed usually on moving the mouse cursor on top of an element.
(like an image or a link). The qTip jQuery plugin is good to show tool tips.

jQuery is a great JavaScript Library. You can learn it here

Here are the steps to create some cool tool tips:

For the elements that you need the tooltip, give a unique id attribute. For this example, we add an id attribute to the hyper link like this:

<a href='#' id='link_example1'>The tooltip Link</a>

Now, add the following code to your page within the <head> and </head> tags:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="jquery.qtip-1.0.0-rc3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
    $('#link_example1').qtip(
    {
     content:'A simple tooltip for the link',
     style: {name: 'dark', tip: 'topLeft'}
    });
});
</script>

The first line adds jQuery to to your page. If you already have jQuery included in your page, no need to add that line.
The second line adds the tooltip library qTip. (You can download the script from here and don’t forget to upload the script to your website )

The line below creates the tooltip:

$('#link_example1').qtip(
    {
     content:'A simple tooltip for the link',
     style: {name: 'dark', tip: 'topLeft'}
    });

As you might have noticed, this attaches the tooltip to the element with the unique IDlink_example1

See the jQuery tooltip demo here

The qTip jQuery plugin has a huge set of customizable options. See the documentation.

Popup on clicking a link

Colorbox is another good Popup jQuery plugin. The example below shows how to open a modal popup when a link is clicked

First, the link:

<a href='content_help.html' id='link_content' >Help Link</a>

Notice that the link points to ‘content_help.html’ we want to open ‘content_help.html’ in a popup.

Now, the popup code:
Put the code below between <head> and </head> tags of your page.

<link media="screen" rel="stylesheet" href="colorbox.css" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="jquery.colorbox-min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function()
    {
        $('#link_content').colorbox({opacity:0.3});
    });
</script>

Notice that the ID of the link is link_content.

The code below opens the popup.

$('#link_content').colorbox({opacity:0.3});

You can provide any valid link (like an image ) in he href attribute of the link. The colorbox plugin grabs it and puts it in the popup.

See the Popup demo here

For more options and customization, see the colorbox documentation page

Opening a popup on loading the page

We can use Colorbox plugin to open a popup on loading the page as well.
Here is the code (put it inside <head> and </head> tags of your page ) :

<link media="screen" rel="stylesheet" href="colorbox.css" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="jquery.colorbox-min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function()
{
    $(window).bind('load',
        function(e)
        {
            $.colorbox({opacity:0.3, href:"offer.html"});
        });
});
</script>

The code opens the page “offer.html” in the popup:

$.colorbox({opacity:0.3, href:"offer.html"});

See the popup demo here

Delayed popup

A slight change in the code above can delay the popup for a few seconds.

$(function()
{
$(window).bind('load',
    function(e)
    {
    window.setTimeout(function()
        {
         $.colorbox({opacity:0.3, href:"offer.html"});
        }, /*timeout->*/ 2000);
    });
});

Delayed popup demo

You can download the samples here

2. Using the window.open method in JAVASCRIPT POPUP WINDOWS

The syntax of the window.open method is given below:
open (URL, windowName[, windowFeatures])

URL
The URL of the page to open in the new window. This argument could be blank.

windowName
A name to be given to the new window. The name can be used to refer this window again.

windowFeatures
A string that determines the various window features to be included in the popup window (like status bar, address bar etc)

The following code opens a new browser window with standard features.

window.open ("http://www.javascript-coder.com","mywindow");

Changing the features of the Popup

You can control the features of the popup using the last argument to the window.open method. The following code opens a window with a status bar and no extra features.

window.open ("http://www.javascript-coder.com","mywindow","status=1");

The code below opens a window with toolbar and status bar.

window.open ("http://www.javascript-coder.com", "mywindow","status=1,toolbar=1");

The table shows the features and the string tokens you can use:

status The status bar at the bottom of the window.
toolbar The standard browser toolbar, with buttons such as Back and Forward.
location The Location entry field where you enter the URL.
menubar The menu bar of the window
directories The standard browser directory buttons, such as What’s New and What’s Cool
resizable Allow/Disallow the user to resize the window.
scrollbars Enable the scrollbars if the document is bigger than the window
height Specifies the height of the window in pixels. (example: height=’350′)
width Specifies the width of the window in pixels.

Examples

The following code opens a window with menu bar. The window is re-sizable and is having 350 pixels width and 250 pixels height.

window.open ("http://www.javascript-coder.com","mywindow","menubar=1,resizable=1,width=350,height=250");

Example 1

A window with location bar, status bar, scroll bar and of size 100 X 100

window.open ("http://www.javascript-coder.com", "mywindow","location=1,status=1,scrollbars=1, width=100,height=100");

Example 2

Moving the window to a desired location

You can use the window.moveTo function to move the popup window to a desired location.
The code below shows positioning the popup at a desired location.

function mypopup()
{
    mywindow = window.open("http://www.javascript-coder.com", "mywindow", "location=1,status=1,scrollbars=1,  width=100,height=100");
    mywindow.moveTo(0, 0);
}

The code positions the popup on the top left corner of the screen.

Putting it all together

Now we will combine all these information to create the popup windows of different types.
The Code below opens a popup window when you enter the page:

<html>
<head>
 <title>JavaScript Popup Example 3</title>
</head>
<script type="text/javascript">
function poponload()
{
    testwindow = window.open("", "mywindow", "location=1,status=1,scrollbars=1,width=100,height=100");
    testwindow.moveTo(0, 0);
}
</script>
<body onload="javascript: poponload()">
<h1>JavaScript Popup Example 3</h1>
</body>
</html>

Notice that the URL is kept blank. This will open a blank window. You can see the code in work in this file:
JavaScript Popup Example 3

Popup On Exit

The following code pops up a window when the user exits a page.

<html>
<head>
 <title>JavaScript Popup Example 3</title>
</head>
<script type="text/javascript">
function exitpop()
{
    my_window = window.open("", "mywindow1", "status=1,width=350,height=150");
    my_window.document.write('<h1>Popup Test!</h1>');
}
</script>
<body onunload="javascript: exitpop()" >
<h1>JavaScript Popup Example 4</h1>
</body>
</html>

The code contains an extra line:

my_window.document.write('<h1>Popup Test!</h1>')

This code displays a line ‘Popup Test!’ in the popup.

The code is available in the file:
JavaScript Popup Example 4

Popups

See section 6B of the book.

Sometimes it’s useful to add a popup to your pages. When the user clicks on a link, a new window opens and displays a page.

There are two ways to do this. You can add a TARGET=”_blank” to the<a>-tag, but this simply opens a new browser window that completely obscures the old one.

This may be what you want, but at other times a small window on top of the large browser window is much better. This small window is popularly known as a popup.

First the basic syntax of how to create a popup, then an explanation of the script, including a table of the most common arguments you can give to a popup and the problem of focusing.
Then a new way of adding popup behaviour to a link. This site uses the new system because it’s much cleaner than the old one.
Finally some notes about writing content directly into the popup. This gives several problems, most importantly the confusion over exactly what the URL of the popup is.

Creating a popup

To create a popup you’ll need the following script:

<script language="javascript" type="text/javascript">
<!--
function popitup(url) {
	newwindow=window.open(url,'name','height=200,width=150');
	if (window.focus) {newwindow.focus()}
	return false;
}

// -->
</script>

Then, you link to it by:

<a href="popupex.html" onclick="return popitup('popupex.html')"
	>Link to popup</a>

Open popup.

See below for a far cleaner way of adding popup behaviour to a link.

Explanation

First, you open the new window. The page to be opened is passed on by the argument url. Note that, if you want to open a page on another server, Explorer will frequently give errors. This is a feature, not a bug, so there’s little you can do about it.

You have to give a name to the window (in this case, name). This name can be used as the target of a link.

In addition, you have to load the window into a JavaScript variable. The reasons for this are complex and have mostly to do with preventing errors in various browsers, especially when you want more links to lead to the same popup.

function popitup(url) {
	newwindow=window.open(url,'name','height=200,width=150');

Arguments

So first we define the url to be loaded in the popup and then the useless name.

As third argument, you can assign all kinds of variables. Most common are height and width, which define the height and width of the new window.

'height=200,width=150'

As soon as you define anything, all yes | no arguments that you have not defined are set to no.
Warning: Spaces or hard returns are not allowed within the quote-marks.

Open popup, and set the arguments through the checkboxes below.

dependent
directories
fullscreen
location
menubar
resizable
scrollbars
status
toolbar

top=200
left=400
width=200
height=200
screenX=400
screenY=200

Focus

Then we place the focus on the new window so that it’s on top of the main window. First check if the browser supports the focus() method, if so place the focus on the new window.

	if (window.focus) {newwindow.focus()}

Accessibility

Finally we return false. This is to prevent the browser from following the actual link.

	return false;
}

When calling the script, make sure you do this:

<a href="popupex.html" onclick="return popitup('popupex.html')"
	>Link to popup</a>

The normal link leads to the page you want to show, while the popup script is called in the onclick event handler. When the script is called, it returns false to prevent the browser from following the link.

The trick is that when JavaScript is disabled and the popup script doesn’t work, the link simply leads to the page. Thus your popups remain perfectly accessible.

Custom attributes

When I created QuirksMode.org I became heartily sick and tired of the ugliness of the HTML of popup links. Therefore I invented a new system. I declare popup links as follows:

<p>See also the <a href="../key.html" type="popup"
	>key</a> to my compatibility tables.</p>

Note the custom type="popup" attribute. Each time you load a new page, an onload script is executed. One of the things it does is:

var x = document.getElementsByTagName('a');
for (var i=0;i<x.length;i++) {
	if (x[i].getAttribute('type') == 'popup') {
		x[i].onclick = function () {
			return pop(this.href)
		}
		x[i].title += ' (Popup)';
	}
}

I go through all links on the page and check for this attribute. If the script finds it, it adds an onclick event handler:

		x[i].onclick = function () {
			return pop(this.href)
		}

The event handler calls the function pop() (which is almost the same as the test function popitup() I use on this page). It passes this.href as an argument, which is the actual href of the link the user clicked on. pop()returns false for the accessibility reasons I described above, and the event handler returns it to the event, so that the actual link is not followed.

Simple and clean, works in all browsers. The only slight disadvantage is that no current XHTML specification allows the use of custom attributes. Personally I don’t care, but if you wish to write flawless XHTML you cannot use this technique.

Writing into popups

Writing the content directly into the popup does not work in Explorer 3 on Windows, Konqueror 2.2.2 and Omniweb.

As you’ve seen above, you can load a new page into the popup. However it’s also possible to write the content into the popup by means of JavaScript. This has the advantage that you don’t need to write an entirely new page for display in the popup, but it also has disadvantages.

First of all, try it.

This is done as follows:

function popitup2() {
	newwindow2=window.open('','name','height=200,width=150');
	var tmp = newwindow2.document;
	tmp.write('<html><head><title>popup</title>');
	tmp.write('<link rel="stylesheet" href="js.css">');
	tmp.write('</head><body><p>this is once again a popup.</p>');
	tmp.write('<p><a href="javascript:alert(self.location.href)">view location</a>.</p>');
	tmp.write('<p><a href="javascript:self.close()">close</a> the popup.</p>');
	tmp.write('</body></html>');
	tmp.close();
}

As you see, open the window, write the HTML into newwindow2.documentand it works. The document.close() at the end is something different than a window.close(), it kind of means that the document inside the popup is closed for writing. I found out this statement is necessary in Netscape 2, 3 and 4 to see anything at all and in Opera 5 when you want to open the popup more than once. Without the statement you can open it only once, the next time you click on the link nothing happens.

Explorer 4 on Windows

Explorer 4 on Windows is a problematical browser. First it steadfastly refused to execute the script above, even when I changed everydocument.write to a document.writeln on the advice of a reader. Then when I restarted my computer, Explorer 4 always executed the script correctly, whatever the exact code. At the moment I’m not sure if it supports this way of writing to a popup or not. It seems to work.

So I do not guarantee Explorer 4 compatibility, but the script will probably work.

The URL of the popup

Opera 3 and Hotjava 3 give ‘blank‘ as the URL of the popup, while Opera 5 on Mac thinks it is ~i.

Opera 5.11- on Windows and Linux crash on the View Location link.

There’s one catch however: what exactly is the URL of the page in the popup? As you might have expected, different browsers have different opinions. I put a link ‘View location’ in the popup that displays thelocation.href of the page. Usually the location is this page, popup.html, that’s because the browser sees the popup as a kind of extended part of this page.

I noticed this problem because a colleague of mine wanted to use this sort of script for making a printer friendly version of a page. Write the content into a popup, with minimal markup, and then let the user press ‘Print’. Unfortunately most browsers printed out the main page because they executed the print() command for the location.href (the main page), which was not at all what he had in mind.

Interestingly, the self.close() command always correctly closes the popup, not the main page.

Related posts:

  1. Using the window.close method
  2. JavaScript Popup Windows
  3. Can JavaScript email a form?
  4. The HTML Form Tag
  5. How to get the value of a form element using JavaScript
  6. JavaScript Button
  7. How to make a web form and get it online quickly
  8. How to use getElementById to get the elements in a form
  9. How to make a web form
  10. How to get the value of a form element : check box and radio button
  11. HTML Form Tutorial Part III : Still More Input Elements
  12. Simfatic Forms Validation: save your time coding
  13. HTML Form Tutorial

var _gaq = _gaq || [];
_gaq.push([‘_setAccount’, ‘UA-33453339-1’]);
_gaq.push([‘_trackPageview’]);

(function() {
var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
ga.src = (‘https:’ == document.location.protocol ? ‘https://&#8217; : ‘http://&#8217;) + ‘stats.g.doubleclick.net/dc.js’;
var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
})();

14 thoughts on “JavaScript – Samples

  1. Hello presently there. I found your site using bing. This generally is a very well crafted article. I shall be bound for you to bookmark this and application discover more of ones useful data. Was looking for post. Ill definitely return.

  2. Woah! I’m really loving the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance”
    between usability and appearance. I must say you’ve done a superb job with this.
    Also, the blog loads very fast for me on Internet explorer.
    Excellent Blog!

  3. Having read this I believed it was rather informative.
    I appreciate you taking the time and effort to put this informative article
    together. I once again find myself spending way too
    much time both reading and leaving comments. But so what, it was still worth it!

  4. I like what you guys tend to be up too. This sort of clever work and
    coverage! Keep up the good works guys I’ve incorporated
    you guys to my personal blogroll.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s