Post Link Sharing: Css & Jav

Header Ads Widget

ad728
Showing posts with label Css & Jav. Show all posts
Showing posts with label Css & Jav. Show all posts
JavaScript Tutorials

JavaScript Tutorials

    Introduction

    What is JavaScript ?

    JavaScript is a dynamic computer programming language. It is lightweight and most commonly used as a part of web pages, whose implementations allow client-side script to interact with the user and make dynamic pages. It is an interpreted programming language with object-oriented capabilities.

    JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. 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 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 not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content.

    The JavaScript client-side mechanism provides 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 initiates explicitly or implicitly.

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

    We cannot 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 cannot be used for networking applications because there is no such support available.

    • JavaScript doesn't have any multi-threading or multiprocessor 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 major strengths of JavaScript is that it does not require expensive development tools. 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. Some 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 interactive websites.

    • 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 − HomeSite 5 is a well-liked HTML and JavaScript editor from Macromedia that can be used to manage personal websites effectively.

    Where is JavaScript Today ?

    The ECMAScript Edition 5 standard will be the first update to be released in over four years. JavaScript 2.0 conforms to Edition 5 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 both the languages still support the features that are not a part of the standard.

    Syntax

    JavaScript can be implemented using JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.

    You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is normally recommended that you should keep it within the <head> tags.

    The <script> tag alerts the browser program to start interpreting all the text between these tags as a script. A simple syntax of your JavaScript will appear 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 Code

    Let us take a sample example to print out "Hello World". 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 as a piece of JavaScript code. Next, we call a function document.writewhich writes a string into our HTML document.

    This function can be used to write text, HTML, or both. Take a look at the following code.

     Live Demo

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

    This code will produce the following result −

    Hello World!
    

    Whitespace and Line Breaks

    JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your program and 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 each of your statements are 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, you must use semicolons −

    <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 the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

    So the identifiers Time and TIME will convey different meanings in JavaScript.

    NOTE − Care should be taken while writing 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

    The following example shows how to use comments in JavaScript.

    <script language = "javascript" type = "text/javascript">
       <!--
          // This is a comment. It is similar to comments in C++
       
          /*
          * This is a multi-line comment in JavaScript
          * It is very similar to comments in C Programming
          */
       //-->
    </script>

    Valiables

    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 as object. We will cover objects in detail in a separate chapter.

    Note − JavaScript 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 at a later point in time when you need that variable.

    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 at 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 variables have only two scopes.

    • Global Variables − A global variable has global scope which means it can be defined anywhere 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. Take a look into the following example.

     Live Demo

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

    This produces the following result −

    local
    

    JavaScript Variable Names

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

    • You should not use any of the JavaScript reserved keywords as a 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 an 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 nameare two different variables.

    JavaScript Reserved Words

    A list of all the reserved words in JavaScript are given in the following table. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.

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

    Operators

    What is an Operator?

    Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operandsand ‘+’ is called the operator. JavaScript supports the following types of operators.

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

    Lets have a look on all operators one by one.

    Arithmetic Operators

    JavaScript supports the following arithmetic operators −

    Assume variable A holds 10 and variable B holds 20, then −

    Sr.No. Operator & Description
    1

    + (Addition)

    Adds two operands

    Ex: A + B will give 30

    2

    - (Subtraction)

    Subtracts the second operand from the first

    Ex: A - B will give -10

    3

    * (Multiplication)

    Multiply both operands

    Ex: A * B will give 200

    4

    / (Division)

    Divide the numerator by the denominator

    Ex: B / A will give 2

    5

    % (Modulus)

    Outputs the remainder of an integer division

    Ex: B % A will give 0

    6

    ++ (Increment)

    Increases an integer value by one

    Ex: A++ will give 11

    7

    -- (Decrement)

    Decreases an integer value by one

    Ex: A-- will give 9

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

    Example

    The following code shows how to use arithmetic operators in JavaScript.

     Live Demo

    <html>
       <body>
       
          <script type = "text/javascript">
             <!--
                var a = 33;
                var b = 10;
                var c = "Test";
                var linebreak = "<br />";
             
                document.write("a + b = ");
                result = a + b;
                document.write(result);
                document.write(linebreak);
             
                document.write("a - b = ");
                result = a - b;
                document.write(result);
                document.write(linebreak);
             
                document.write("a / b = ");
                result = a / b;
                document.write(result);
                document.write(linebreak);
             
                document.write("a % b = ");
                result = a % b;
                document.write(result);
                document.write(linebreak);
             
                document.write("a + b + c = ");
                result = a + b + c;
                document.write(result);
                document.write(linebreak);
             
                a = ++a;
                document.write("++a = ");
                result = ++a;
                document.write(result);
                document.write(linebreak);
             
                b = --b;
                document.write("--b = ");
                result = --b;
                document.write(result);
                document.write(linebreak);
             //-->
          </script>
          
          Set the variables to different values and then try...
       </body>
    </html>

    Output

    a + b = 43
    a - b = 23
    a / b = 3.3
    a % b = 3
    a + b + c = 43Test
    ++a = 35
    --b = 8
    Set the variables to different values and then try...
    

    Comparison Operators

    JavaScript supports the following comparison operators −

    Assume variable A holds 10 and variable B holds 20, then −

    Sr.No. Operator & Description
    1

    = = (Equal)

    Checks if the value of two operands are equal or not, if yes, then the condition becomes true.

    Ex: (A == B) is not true.

    2

    != (Not Equal)

    Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes true.

    Ex: (A != B) is true.

    3

    > (Greater than)

    Checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition becomes true.

    Ex: (A > B) is not true.

    4

    < (Less than)

    Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition becomes true.

    Ex: (A < B) is true.

    5

    >= (Greater than or Equal to)

    Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition becomes true.

    Ex: (A >= B) is not true.

    6

    <= (Less than or Equal to)

    Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition becomes true.

    Ex: (A <= B) is true.

    Example

    The following code shows how to use comparison operators in JavaScript.

     Live Demo

    <html>
       <body>  
          <script type = "text/javascript">
             <!--
                var a = 10;
                var b = 20;
                var linebreak = "<br />";
          
                document.write("(a == b) => ");
                result = (a == b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a < b) => ");
                result = (a < b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a > b) => ");
                result = (a > b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a != b) => ");
                result = (a != b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a >= b) => ");
                result = (a >= b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a <= b) => ");
                result = (a <= b);
                document.write(result);
                document.write(linebreak);
             //-->
          </script>      
          Set the variables to different values and different operators and then try...
       </body>
    </html>

    Output

    (a == b) => false 
    (a < b) => true 
    (a > b) => false 
    (a != b) => true 
    (a >= b) => false 
    a <= b) => true
    Set the variables to different values and different operators and then try...
    

    Logical Operators

    JavaScript supports the following logical operators −

    Assume variable A holds 10 and variable B holds 20, then −

    Sr.No. Operator & Description
    1

    && (Logical AND)

    If both the operands are non-zero, then the condition becomes true.

    Ex: (A && B) is true.

    2

    || (Logical OR)

    If any of the two operands are non-zero, then the condition becomes true.

    Ex: (A || B) is true.

    3

    ! (Logical NOT)

    Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.

    Ex: ! (A && B) is false.

    Example

    Try the following code to learn how to implement Logical Operators in JavaScript.

     Live Demo

    <html>
       <body>   
          <script type = "text/javascript">
             <!--
                var a = true;
                var b = false;
                var linebreak = "<br />";
          
                document.write("(a && b) => ");
                result = (a && b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a || b) => ");
                result = (a || b);
                document.write(result);
                document.write(linebreak);
             
                document.write("!(a && b) => ");
                result = (!(a && b));
                document.write(result);
                document.write(linebreak);
             //-->
          </script>      
          <p>Set the variables to different values and different operators and then try...</p>
       </body>
    </html>

    Output

    (a && b) => false 
    (a || b) => true 
    !(a && b) => true
    Set the variables to different values and different operators and then try...
    

    Bitwise Operators

    JavaScript supports the following bitwise operators −

    Assume variable A holds 2 and variable B holds 3, then −

    Sr.No. Operator & Description
    1

    & (Bitwise AND)

    It performs a Boolean AND operation on each bit of its integer arguments.

    Ex: (A & B) is 2.

    2

    | (BitWise OR)

    It performs a Boolean OR operation on each bit of its integer arguments.

    Ex: (A | B) is 3.

    3

    ^ (Bitwise XOR)

    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.

    Ex: (A ^ B) is 1.

    4

    ~ (Bitwise Not)

    It is a unary operator and operates by reversing all the bits in the operand.

    Ex: (~B) is -4.

    5

    << (Left Shift)

    It moves all the 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 it by 2, shifting two positions is equivalent to multiplying by 4, and so on.

    Ex: (A << 1) is 4.

    6

    >> (Right Shift)

    Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand.

    Ex: (A >> 1) is 1.

    7

    >>> (Right shift with Zero)

    This operator is just like the >> operator, except that the bits shifted in on the left are always zero.

    Ex: (A >>> 1) is 1.

    Example

    Try the following code to implement Bitwise operator in JavaScript.

     Live Demo

    <html>
       <body>   
          <script type = "text/javascript">
             <!--
                var a = 2; // Bit presentation 10
                var b = 3; // Bit presentation 11
                var linebreak = "<br />";
             
                document.write("(a & b) => ");
                result = (a & b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a | b) => ");
                result = (a | b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a ^ b) => ");
                result = (a ^ b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(~b) => ");
                result = (~b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a << b) => ");
                result = (a << b);
                document.write(result);
                document.write(linebreak);
             
                document.write("(a >> b) => ");
                result = (a >> b);
                document.write(result);
                document.write(linebreak);
             //-->
          </script>      
          <p>Set the variables to different values and different operators and then try...</p>
       </body>
    </html>
    (a & b) => 2 
    (a | b) => 3 
    (a ^ b) => 1 
    (~b) => -4 
    (a << b) => 16 
    (a >> b) => 0
    Set the variables to different values and different operators and then try...
    

    Assignment Operators

    JavaScript supports the following assignment operators −

    Sr.No. Operator & Description
    1

    = (Simple Assignment )

    Assigns values from the right side operand to the left side operand

    Ex: C = A + B will assign the value of A + B into C

    2

    += (Add and Assignment)

    It adds the right operand to the left operand and assigns the result to the left operand.

    Ex: C += A is equivalent to C = C + A

    3

    −= (Subtract and Assignment)

    It subtracts the right operand from the left operand and assigns the result to the left operand.

    Ex: C -= A is equivalent to C = C - A

    4

    *= (Multiply and Assignment)

    It multiplies the right operand with the left operand and assigns the result to the left operand.

    Ex: C *= A is equivalent to C = C * A

    5

    /= (Divide and Assignment)

    It divides the left operand with the right operand and assigns the result to the left operand.

    Ex: C /= A is equivalent to C = C / A

    6

    %= (Modules and Assignment)

    It takes modulus using two operands and assigns the result to the left operand.

    Ex: C %= A is equivalent to C = C % A

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

    Example

    Try the following code to implement assignment operator in JavaScript.

     Live Demo

    <html>
       <body>   
          <script type = "text/javascript">
             <!--
                var a = 33;
                var b = 10;
                var linebreak = "<br />";
             
                document.write("Value of a => (a = b) => ");
                result = (a = b);
                document.write(result);
                document.write(linebreak);
             
                document.write("Value of a => (a += b) => ");
                result = (a += b);
                document.write(result);
                document.write(linebreak);
             
                document.write("Value of a => (a -= b) => ");
                result = (a -= b);
                document.write(result);
                document.write(linebreak);
             
                document.write("Value of a => (a *= b) => ");
                result = (a *= b);
                document.write(result);
                document.write(linebreak);
             
                document.write("Value of a => (a /= b) => ");
                result = (a /= b);
                document.write(result);
                document.write(linebreak);
             
                document.write("Value of a => (a %= b) => ");
                result = (a %= b);
                document.write(result);
                document.write(linebreak);
             //-->
          </script>      
          <p>Set the variables to different values and different operators and then try...</p>
       </body>
    </html>

    Output

    Value of a => (a = b) => 10
    Value of a => (a += b) => 20 
    Value of a => (a -= b) => 10 
    Value of a => (a *= b) => 100 
    Value of a => (a /= b) => 10
    Value of a => (a %= b) => 0
    Set the variables to different values and different operators and then try...
    

    Miscellaneous Operator

    We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and the typeof operator.

    Conditional Operator (? :)

    The conditional operator first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.

    Sr.No. Operator and Description
    1

    ? : (Conditional )

    If Condition is true? Then value X : Otherwise value Y

    Example

    Try the following code to understand how the Conditional Operator works in JavaScript.

     Live Demo

    <html>
       <body>   
          <script type = "text/javascript">
             <!--
                var a = 10;
                var b = 20;
                var linebreak = "<br />";
             
                document.write ("((a > b) ? 100 : 200) => ");
                result = (a > b) ? 100 : 200;
                document.write(result);
                document.write(linebreak);
             
                document.write ("((a < b) ? 100 : 200) => ");
                result = (a < b) ? 100 : 200;
                document.write(result);
                document.write(linebreak);
             //-->
          </script>      
          <p>Set the variables to different values and different operators and then try...</p>
       </body>
    </html>

    Output

    ((a > b) ? 100 : 200) => 200 
    ((a < b) ? 100 : 200) => 100
    Set the variables to different values and different operators and then try...
    

    typeof Operator

    The typeof operator 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 a list of the 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"

    Example

    The following code shows how to implement typeof operator.

     Live Demo

    <html>
       <body>      
          <script type = "text/javascript">
             <!--
                var a = 10;
                var b = "String";
                var linebreak = "<br />";
             
                result = (typeof b == "string" ? "B is String" : "B is Numeric");
                document.write("Result => ");
                document.write(result);
                document.write(linebreak);
             
                result = (typeof a == "string" ? "A is String" : "A is Numeric");
                document.write("Result => ");
                document.write(result);
                document.write(linebreak);
             //-->
          </script>      
          <p>Set the variables to different values and different operators and then try...</p>
       </body>
    </html>

    Output

    Result => B is String 
    Result => A is Numeric
    Set the variables to different values and different operators and then try...

    If...Else

    While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In such cases, you need to use 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 the if..else statement.

    Flow Chart of if-else

    The following flow chart shows how the if-else statement works.

    Decision Making

    JavaScript supports the 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

    The syntax for a basic if statement is as follows −

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

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

    Example

    Try the following example to understand how the if statement works.

     Live Demo

    <html>
       <body>     
          <script type = "text/javascript">
             <!--
                var age = 20;
             
                if( age > 18 ) {
                   document.write("<b>Qualifies for driving</b>");
                }
             //-->
          </script>      
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    Qualifies for driving
    Set the variable to different value and then try...
    

    if...else statement

    The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a 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, the given statement(s) in the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are executed.

    Example

    Try the following code to learn how to implement an if-else statement in JavaScript.

     Live Demo

    <html>
       <body>   
          <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>     
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    Does not qualify for driving
    Set the variable to different value and then try...
    

    if...else if... statement

    The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.

    Syntax

    The syntax of an if-else-if statement is as follows −

    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 ifis a part of the else clause of the previous statement. Statement(s) are executed based on the true condition, if none of the conditions is true, then the else block is executed.

    Example

    Try the following code to learn how to implement an if-else-if statement in JavaScript.

     Live Demo

    <html>
       <body>   
          <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>      
          <p>Set the variable to different value and then try...</p>
       </body>
    <html>

    Output

    Maths Book
    Set the variable to different value and then try...

    Switch Case

    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.

    Flow Chart

    The following flow chart explains a switch-case statement works.

    Switch case

    Syntax

    The objective of a 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, a default 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 the end of a 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

    Try the following example to implement switch-case statement.

     Live Demo

    <html>
       <body>   
          <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>      
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    Entering switch block
    Good job
    Exiting switch block
    Set the variable to different value and then try...
    

    Break statements play a major role in switch-case statements. Try the following code that uses switch-case statement without any break statement.

     Live Demo

    <html>
       <body>      
          <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>      
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    Entering switch block
    Good job
    Pretty good
    Passed
    Not so good
    Failed
    Unknown grade
    Exiting switch block
    Set the variable to different value and then try...

    While Loop

    While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines.

    JavaScript supports all the necessary loops to ease down the pressure of programming.

    The while Loop

    The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.

    Flow Chart

    The flow chart of while loop looks as follows −

    While loop

    Syntax

    The syntax of while loop in JavaScript is as follows −

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

    Example

    Try the following example to implement while loop.

     Live Demo

    <html>
       <body>
          
          <script type = "text/javascript">
             <!--
                var count = 0;
                document.write("Starting Loop ");
             
                while (count < 10) {
                   document.write("Current Count : " + count + "<br />");
                   count++;
                }
             
                document.write("Loop stopped!");
             //-->
          </script>
          
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    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!
    Set the variable to different value and then try... 
    

    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.

    Flow Chart

    The flow chart of a do-while loop would be as follows −

    Do While Loop

    Syntax

    The syntax for do-while loop in JavaScript is as follows −

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

    Note − Don’t miss the semicolon used at the end of the do...while loop.

    Example

    Try the following example to learn how to implement a do-while loop in JavaScript.

     Live Demo

    <html>
       <body>   
          <script type = "text/javascript">
             <!--
                var count = 0;
                
                document.write("Starting Loop" + "<br />");
                do {
                   document.write("Current Count : " + count + "<br />");
                   count++;
                }
                
                while (count < 5);
                document.write ("Loop stopped!");
             //-->
          </script>      
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    Starting Loop
    Current Count : 0 
    Current Count : 1 
    Current Count : 2 
    Current Count : 3 
    Current Count : 4
    Loop Stopped!
    Set the variable to different value and then try...

    For Loop

    The 'for' loop is the most compact form of looping. It 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 a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.

    • The iteration statement where you can increase or decrease your counter.

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

    Flow Chart

    The flow chart of a for loop in JavaScript would be as follows −

    For Loop

    Syntax

    The syntax of for loop is JavaScript is as follows −

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

    Example

    Try the following example to learn how a for loop works in JavaScript.

     Live Demo

    <html>
       <body>      
          <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>      
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    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! 
    Set the variable to different value and then try...

    Loop Control

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

    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.

    Flow Chart

    The flow chart of a break statement would look as follows −

    Break Statement

    Example

    The following 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 the closing curly brace −

     Live Demo

    <html>
       <body>     
          <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>
          
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    Entering the loop
    2
    3
    4
    5
    Exiting the loop!
    Set the variable to different value and then try...
    

    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 the remaining code block. When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.

    Example

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

     Live Demo

    <html>
       <body>      
          <script type = "text/javascript">
             <!--
                var x = 1;
                document.write("Entering the loop<br /> ");
             
                while (x < 10) {
                   x = x + 1;
                   
                   if (x == 5) {
                      continue;   // skip rest of the loop body
                   }
                   document.write( x + "<br />");
                }         
                document.write("Exiting the loop!<br /> ");
             //-->
          </script>      
          <p>Set the variable to different value and then try...</p>
       </body>
    </html>

    Output

    Entering the loop
    2
    3
    4
    6
    7
    8
    9
    10
    Exiting the loop!
    Set the variable to different value and then try...
    

    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. A label is simply an identifier followed by a colon (:) that is applied to a statement or a block of code. We will see two different examples to understand how to use labels 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.

    Try the following two examples for a better understanding of Labels.

    Example 1

    The following example shows how to implement Label with a break statement.

     Live Demo

    <html>
       <body>      
          <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>      
       </body>
    </html>

    Output

    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!
    

    Example 2

     Live Demo

    <html>
       <body>
       
          <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>
          
       </body>
    </html>

    Output

    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

    A function is a group of reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.

    Like any other advanced 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 the earlier chapters. We were using these functions again and again, but they had been written in core JavaScript only once.

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

    Function Definition

    Before we use a function, we need to define it. 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.

    Syntax

    The basic syntax is shown here.

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

    Example

    Try the following example. It defines a function called sayHello that takes no parameters −

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

    Calling a Function

    To invoke a function somewhere later in the script, you would simply need to write the name of that function as shown in the following code.

     Live Demo

    <html>
       <head>   
          <script type = "text/javascript">
             function sayHello() {
                document.write ("Hello there!");
             }
          </script>
          
       </head>
       
       <body>
          <p>Click the following button to call the function</p>      
          <form>
             <input type = "button" onclick = "sayHello()" value = "Say Hello">
          </form>      
          <p>Use different text in write method and then try...</p>
       </body>
    </html>

    Output

    Function Parameters

    Till now, we have seen functions without 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

    Try the following example. We have modified our sayHello function here. Now it takes two parameters.

     Live Demo

    <html>
       <head>   
          <script type = "text/javascript">
             function sayHello(name, age) {
                document.write (name + " is " + age + " years old.");
             }
          </script>      
       </head>
       
       <body>
          <p>Click the following button to call the function</p>      
          <form>
             <input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">
          </form>      
          <p>Use different parameters inside the function and then try...</p>
       </body>
    </html>

    Output

    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 the function to return their multiplication in your calling program.

    Example

    Try the following example. It defines a function that takes two parameters and concatenates them before returning the resultant in the calling program.

     Live Demo

    <html>
       <head>  
          <script type = "text/javascript">
             function concatenate(first, last) {
                var full;
                full = first + last;
                return full;
             }
             function secondFunction() {
                var result;
                result = concatenate('Zara', 'Ali');
                document.write (result );
             }
          </script>      
       </head>
       
       <body>
          <p>Click the following button to call the function</p>      
          <form>
             <input type = "button" onclick = "secondFunction()" value = "Call Function">
          </form>      
          <p>Use different parameters inside the function and then try...</p>  
      </body>
    </html>

    Output

    There is a lot to learn about JavaScript functions, however we have covered the most important concepts in this tutorial.

    Events

    What is an Event ?

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

    When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a 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.

    Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a 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 a 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 the left button of his mouse. You can put your validation, warning etc., against this event type.

    Example

    Try the following example.

     Live Demo

    <html>
       <head>   
          <script type = "text/javascript">
             <!--
                function sayHello() {
                   alert("Hello World")
                }
             //-->
          </script>      
       </head>
       
       <body>
          <p>Click the following button and see result</p>      
          <form>
             <input type = "button" onclick = "sayHello()" value = "Say Hello" />
          </form>      
       </body>
    </html>

    Output

    onsubmit Event Type

    onsubmit is an event that occurs when you try to submit a form. You can put your form validation against this event type.

    Example

    The following example shows how to use onsubmit. 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.

    Try the following 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 create nice effects with images or even with text as well. The onmouseover event triggers when you bring your mouse over any element and the onmouseout triggers when you move your mouse out from that element. Try the following example.

     Live Demo

    <html>
       <head>   
          <script type = "text/javascript">
             <!--
                function over() {
                   document.write ("Mouse Over");
                }            
                function out() {
                   document.write ("Mouse Out");
                }            
             //-->
          </script>      
       </head>
       
       <body>
          <p>Bring your mouse inside the division to see the result:</p>      
          <div onmouseover = "over()" onmouseout = "out()">
             <h2> This is inside the division </h2>
          </div>         
       </body>
    </html>

    Output

    HTML 5 Standard Events

    The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript function to be executed against that event.

    Attribute Value Description
    Offline script Triggers when the document goes offline
    Onabort script Triggers on an abort event
    onafterprint script Triggers after the document is printed
    onbeforeonload script Triggers before the document loads
    onbeforeprint script Triggers before the document is printed
    onblur script Triggers when the window loses focus
    oncanplay script Triggers when media can start play, but might has to stop for buffering
    oncanplaythrough script Triggers when media can be played to the end, without stopping for buffering
    onchange script Triggers when an element changes
    onclick script Triggers on a mouse click
    oncontextmenu script Triggers when a context menu is triggered
    ondblclick script Triggers on a mouse double-click
    ondrag script Triggers when an element is dragged
    ondragend script Triggers at the end of a drag operation
    ondragenter script Triggers when an element has been dragged to a valid drop target
    ondragleave script Triggers when an element is being dragged over a valid drop target
    ondragover script Triggers at the start of a drag operation
    ondragstart script Triggers at the start of a drag operation
    ondrop script Triggers when dragged element is being dropped
    ondurationchange script Triggers when the length of the media is changed
    onemptied script Triggers when a media resource element suddenly becomes empty.
    onended script Triggers when media has reach the end
    onerror script Triggers when an error occur
    onfocus script Triggers when the window gets focus
    onformchange script Triggers when a form changes
    onforminput script Triggers when a form gets user input
    onhaschange script Triggers when the document has change
    oninput script Triggers when an element gets user input
    oninvalid script Triggers when an element is invalid
    onkeydown script Triggers when a key is pressed
    onkeypress script Triggers when a key is pressed and released
    onkeyup script Triggers when a key is released
    onload script Triggers when the document loads
    onloadeddata script Triggers when media data is loaded
    onloadedmetadata script Triggers when the duration and other media data of a media element is loaded
    onloadstart script Triggers when the browser starts to load the media data
    onmessage script Triggers when the message is triggered
    onmousedown script Triggers when a mouse button is pressed
    onmousemove script Triggers when the mouse pointer moves
    onmouseout script Triggers when the mouse pointer moves out of an element
    onmouseover script Triggers when the mouse pointer moves over an element
    onmouseup script Triggers when a mouse button is released
    onmousewheel script Triggers when the mouse wheel is being rotated
    onoffline script Triggers when the document goes offline
    onoine script Triggers when the document comes online
    ononline script Triggers when the document comes online
    onpagehide script Triggers when the window is hidden
    onpageshow script Triggers when the window becomes visible
    onpause script Triggers when media data is paused
    onplay script Triggers when media data is going to start playing
    onplaying script Triggers when media data has start playing
    onpopstate script Triggers when the window's history changes
    onprogress script Triggers when the browser is fetching the media data
    onratechange script Triggers when the media data's playing rate has changed
    onreadystatechange script Triggers when the ready-state changes
    onredo script Triggers when the document performs a redo
    onresize script Triggers when the window is resized
    onscroll script Triggers when an element's scrollbar is being scrolled
    onseeked script Triggers when a media element's seeking attribute is no longer true, and the seeking has ended
    onseeking script Triggers when a media element's seeking attribute is true, and the seeking has begun
    onselect script Triggers when an element is selected
    onstalled script Triggers when there is an error in fetching media data
    onstorage script Triggers when a document loads
    onsubmit script Triggers when a form is submitted
    onsuspend script Triggers when the browser has been fetching media data, but stopped before the entire media file was fetched
    ontimeupdate script Triggers when media changes its playing position
    onundo script Triggers when a document performs an undo
    onunload script Triggers when the user leaves the document
    onvolumechange script Triggers when media changes the volume, also when volume is set to "mute"
    onwaiting script Triggers when media has stopped playing, but is expected to resume

    Cookies

    What are Cookies ?

    Web Browsers and Servers use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. But how to maintain users' session information across all the web pages.

    In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.

    How It Works ?

    Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the browser sends the same cookie to the server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.

    Cookies are a plain text data record of 5 variable-length fields −

    • Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.

    • Domain − The domain name of your site.

    • Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page.

    • Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.

    • Name=Value − Cookies are set and retrieved in the form of key-value pairs

    Cookies were originally designed for CGI programming. The data contained in a cookie is automatically transmitted between the web browser and the web server, so CGI scripts on the server can read and write cookie values that are stored on the client.

    JavaScript can also manipulate cookies using the cookie property of the Documentobject. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.

    Storing Cookies

    The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this.

    document.cookie = "key1 = value1;key2 = value2;expires = date";
    

    Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.

    Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may want to use the JavaScript escape() function to encode the value before storing it in the cookie. If you do this, you will also have to use the corresponding unescape() function when you read the cookie value.

    Example

    Try the following. It sets a customer name in an input cookie.

     Live Demo

    <html>
       <head>   
          <script type = "text/javascript">
             <!--
                function WriteCookie() {
                   if( document.myform.customer.value == "" ) {
                      alert("Enter some value!");
                      return;
                   }
                   cookievalue = escape(document.myform.customer.value) + ";";
                   document.cookie = "name=" + cookievalue;
                   document.write ("Setting Cookies : " + "name=" + cookievalue );
                }
             //-->
          </script>      
       </head>
       
       <body>      
          <form name = "myform" action = "">
             Enter name: <input type = "text" name = "customer"/>
             <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
          </form>   
       </body>
    </html>

    Output

    Now your machine has a cookie called name. You can set multiple cookies using multiple key = value pairs separated by comma.

    Reading Cookies

    Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

    You can use strings' split() function to break a string into key and values as follows −

    Example

    Try the following example to get all the cookies.

     Live Demo

    <html>
       <head>   
          <script type = "text/javascript">
             <!--
                function ReadCookie() {
                   var allcookies = document.cookie;
                   document.write ("All Cookies : " + allcookies );
                   
                   // Get all the cookies pairs in an array
                   cookiearray = allcookies.split(';');
                   
                   // Now take key value pair out of this array
                   for(var i=0; i<cookiearray.length; i++) {
                      name = cookiearray[i].split('=')[0];
                      value = cookiearray[i].split('=')[1];
                      document.write ("Key is : " + name + " and Value is : " + value);
                   }
                }
             //-->
          </script>      
       </head>
       
       <body>     
          <form name = "myform" action = "">
             <p> click the following button and see the result:</p>
             <input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
          </form>      
       </body>
    </html>

    Note − Here length is a method of Array class which returns the length of an array. We will discuss Arrays in a separate chapter. By that time, please try to digest it.

    Note − There may be some other cookies already set on your machine. The above code will display all the cookies set on your machine.

    Setting Cookies Expiry Date

    You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the ‘expires’ attribute to a date and time.

    Example

    Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.

     Live Demo

    <html>
       <head>   
          <script type = "text/javascript">
             <!--
                function WriteCookie() {
                   var now = new Date();
                   now.setMonth( now.getMonth() + 1 );
                   cookievalue = escape(document.myform.customer.value) + ";"
                   
                   document.cookie = "name=" + cookievalue;
                   document.cookie = "expires=" + now.toUTCString() + ";"
                   document.write ("Setting Cookies : " + "name=" + cookievalue );
                }
             //-->
          </script>      
       </head>
       
       <body>
          <form name = "myform" action = "">
             Enter name: <input type = "text" name = "customer"/>
             <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
          </form>      
       </body>
    </html>

    Output

    Deleting a Cookie

    Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.

    Example

    Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.

     Live Demo

    <html>
       <head>   
          <script type = "text/javascript">
             <!--
                function WriteCookie() {
                   var now = new Date();
                   now.setMonth( now.getMonth() - 1 );
                   cookievalue = escape(document.myform.customer.value) + ";"
                   
                   document.cookie = "name=" + cookievalue;
                   document.cookie = "expires=" + now.toUTCString() + ";"
                   document.write("Setting Cookies : " + "name=" + cookievalue );
                }
              //-->
          </script>      
       </head>
       
       <body>
          <form name = "myform" action = "">
             Enter name: <input type = "text" name = "customer"/>
             <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
          </form>      
       </body>
    </html>

    Output

    HTML DOM

    Every web page resides inside a browser window which can be considered as an object.

    A Document object represents the HTML document that is displayed in that window. The Document object has various properties that refer to other objects which allow access to and modification of document content.

    The way a document content is accessed and modified is called the Document Object Model, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies to the organization of objects in a Web document.

    • Window object − Top of the hierarchy. It is the outmost element of the object hierarchy.

    • Document object − Each HTML document that gets loaded into a window becomes a document object. The document contains the contents of the page.

    • Form object − Everything enclosed in the <form>...</form> tags sets the form object.

    • Form control elements − The form object contains all the elements defined for that object such as text fields, buttons, radio buttons, and checkboxes.

    Here is a simple hierarchy of a few important objects −

    HTML DOM

    There are several DOMs in existence. The following sections explain each of these DOMs in detail and describe how you can use them to access and modify document content.

    • The Legacy DOM − This is the model which was introduced in early versions of JavaScript language. It is well supported by all browsers, but allows access only to certain key portions of documents, such as forms, form elements, and images.

    • The W3C DOM − This document object model allows access and modification of all document content and is standardized by the World Wide Web Consortium (W3C). This model is supported by almost all the modern browsers.

    • The IE4 DOM − This document object model was introduced in Version 4 of Microsoft's Internet Explorer browser. IE 5 and later versions include support for most basic W3C DOM features.

    DOM compatibility

    If you want to write a script with the flexibility to use either W3C DOM or IE 4 DOM depending on their availability, then you can use a capability-testing approach that first checks for the existence of a method or property to determine whether the browser has the capability you desire. For example −

    if (document.getElementById) {
       // If the W3C method exists, use it
    } else if (document.all) {
       // If the all[] array exists, use it
    } else {
       // Otherwise use the legacy DOM
    }

    Error Handling

    There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical Errors.

    Syntax Errors

    Syntax errors, also called parsing errors, occur at compile time in traditional programming languages and at interpret time in JavaScript.

    For example, the following line causes a syntax error because it is missing a closing parenthesis.

    <script type = "text/javascript">
       <!--
          window.print(;
       //-->
    </script>
    

    When a syntax error occurs in JavaScript, only the code contained within the same thread as the syntax error is affected and the rest of the code in other threads gets executed assuming nothing in them depends on the code containing the error.

    Runtime Errors

    Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).

    For example, the following line causes a runtime error because here the syntax is correct, but at runtime, it is trying to call a method that does not exist.

    <script type = "text/javascript">
       <!--
          window.printme();
       //-->
    </script>
    

    Exceptions also affect the thread in which they occur, allowing other JavaScript threads to continue normal execution.

    Logical Errors

    Logic errors can be the most difficult type of errors to track down. These errors are not the result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your script and you do not get the result you expected.

    You cannot catch those errors, because it depends on your business requirement what type of logic you want to put in your program.

    The try...catch...finally Statement

    The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.

    You can catch programmer-generated and runtime exceptions, but you cannot catchJavaScript syntax errors.

    Here is the try...catch...finally block syntax −

    <script type = "text/javascript">
       <!--
          try {
             // Code to run
             [break;]
          } 
          
          catch ( e ) {
             // Code to run if an exception occurs
             [break;]
          }
          
          [ finally {
             // Code that is always executed regardless of 
             // an exception occurring
          }]
       //-->
    </script>

    The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the try block, the exception is placed in e and the catch block is executed. The optional finally block executes unconditionally after try/catch.

    Examples

    Here is an example where we are trying to call a non-existing function which in turn is raising an exception. Let us see how it behaves without try...catch

     Live Demo

    <html>
       <head>      
          <script type = "text/javascript">
             <!--
                function myFunc() {
                   var a = 100;
                   alert("Value of variable a is : " + a );
                }
             //-->
          </script>      
       </head>
       
       <body>
          <p>Click the following to see the result:</p>
          
          <form>
             <input type = "button" value = "Click Me" onclick = "myFunc();" />
          </form>      
       </body>
    </html>

    Output

    Now let us try to catch this exception using try...catch and display a user-friendly message. You can also suppress this message, if you want to hide this error from a user.

     Live Demo

    <html>
       <head>
          
          <script type = "text/javascript">
             <!--
                function myFunc() {
                   var a = 100;
                   try {
                      alert("Value of variable a is : " + a );
                   } 
                   catch ( e ) {
                      alert("Error: " + e.description );
                   }
                }
             //-->
          </script>
          
       </head>
       <body>
          <p>Click the following to see the result:</p>
          
          <form>
             <input type = "button" value = "Click Me" onclick = "myFunc();" />
          </form>
          
       </body>
    </html>

    Output

    You can use finally block which will always execute unconditionally after the try/catch. Here is an example.

     Live Demo

    <html>
       <head>
          
          <script type = "text/javascript">
             <!--
                function myFunc() {
                   var a = 100;
                   
                   try {
                      alert("Value of variable a is : " + a );
                   }
                   catch ( e ) {
                      alert("Error: " + e.description );
                   }
                   finally {
                      alert("Finally block will always execute!" );
                   }
                }
             //-->
          </script>
          
       </head>
       <body>
          <p>Click the following to see the result:</p>
          
          <form>
             <input type = "button" value = "Click Me" onclick = "myFunc();" />
          </form>
          
       </body>
    </html>

    Output

    The throw Statement

    You can use throw statement to raise your built-in exceptions or your customized exceptions. Later these exceptions can be captured and you can take an appropriate action.

    Example

    The following example demonstrates how to use a throw statement.

     Live Demo

    <html>
       <head>
          
          <script type = "text/javascript">
             <!--
                function myFunc() {
                   var a = 100;
                   var b = 0;
                   
                   try {
                      if ( b == 0 ) {
                         throw( "Divide by zero error." ); 
                      } else {
                         var c = a / b;
                      }
                   }
                   catch ( e ) {
                      alert("Error: " + e );
                   }
                }
             //-->
          </script>
          
       </head>
       <body>
          <p>Click the following to see the result:</p>
          
          <form>
             <input type = "button" value = "Click Me" onclick = "myFunc();" />
          </form>
          
       </body>
    </html>

    Output

    You can raise an exception in one function using a string, integer, Boolean, or an object and then you can capture that exception either in the same function as we did above, or in another function using a try...catch block.

    The onerror() Method

    The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page.

     Live Demo

    <html>
       <head>
          
          <script type = "text/javascript">
             <!--
                window.onerror = function () {
                   alert("An error occurred.");
                }
             //-->
          </script>
          
       </head>
       <body>
          <p>Click the following to see the result:</p>
          
          <form>
             <input type = "button" value = "Click Me" onclick = "myFunc();" />
          </form>
          
       </body>
    </html>

    Output

    The onerror event handler provides three pieces of information to identify the exact nature of the error −

    • Error message − The same message that the browser would display for the given error

    • URL − The file in which the error occurred

    • Line number− The line number in the given URL that caused the error

    Here is the example to show how to extract this information.

    Example

     Live Demo

    <html>
       <head>
       
          <script type = "text/javascript">
             <!--
                window.onerror = function (msg, url, line) {
                   alert("Message : " + msg );
                   alert("url : " + url );
                   alert("Line number : " + line );
                }
             //-->
          </script>
          
       </head>
       <body>
          <p>Click the following to see the result:</p>
          
          <form>
             <input type = "button" value = "Click Me" onclick = "myFunc();" />
          </form>
          
       </body>
    </html>

    Output

    You can display extracted information in whatever way you think it is better.

    You can use an onerror method, as shown below, to display an error message in case there is any problem in loading an image.

    <img src="myimage.gif" onerror="alert('An error occurred loading the image.')" />

    You can use onerror with many HTML tags to display appropriate messages in case of errors.

    Animation

    You can use JavaScript to create a complex animation having, but not limited to, the following elements −

    • 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 provides a basic understanding of 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 the 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 duration milliseconds.

    • 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 its 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. The following list contains different DOM methods.

    • We are using the 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 its position and left attributes.

    • We are calling initialization function at the time of window load.

    • Finally, we are calling moveRight() function to increase the left distance by 10 pixels. You could also set it to a negative value to move it to the left side.

    Example

    Try the following example.

     Live Demo

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

    Output

    Automated Animation

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

    Here we have added more methods. 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.

    Example

    Try the following example code.

     Live Demo

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

    Rollover with a Mouse Event

    Here is a simple example showing image rollover with a mouse event.

    Let's see what we are using in the following example −

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

    • Similarly, 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.

     Live Demo

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

    Browser

    It is important to understand the differences between different browsers in order to handle each in the way it is expected. So it is important to know which browser your web page is running in.

    To get information about the browser your webpage is currently running in, use the built-in navigator object.

    Navigator Properties

    There are several Navigator related properties that you can use in your Web page. The following is a list of the names and descriptions of each.

    Sr.No. Property & Description
    1

    appCodeName

    This property is a string that contains the code name of the browser, Netscape for Netscape and Microsoft Internet Explorer for Internet Explorer.

    2

    appVersion

    This property is a string that contains the version of the browser as well as other useful information such as its language and compatibility.

    3

    language

    This property contains the two-letter abbreviation for the language that is used by the browser. Netscape only.

    4

    mimTypes[]

    This property is an array that contains all MIME types supported by the client. Netscape only.

    5

    platform[]

    This property is a string that contains the platform for which the browser was compiled."Win32" for 32-bit Windows operating systems

    6

    plugins[]

    This property is an array containing all the plug-ins that have been installed on the client. Netscape only.

    7

    userAgent[]

    This property is a string that contains the code name and version of the browser. This value is sent to the originating server to identify the client.

    Navigator Methods

    There are several Navigator-specific methods. Here is a list of their names and descriptions.

    Sr.No. Description
    1

    javaEnabled()

    This method determines if JavaScript is enabled in the client. If JavaScript is enabled, this method returns true; otherwise, it returns false.

    2

    plugings.refresh

    This method makes newly installed plug-ins available and populates the plugins array with all new plug-in names. Netscape only.

    3

    preference(name,value)

    This method allows a signed script to get and set some Netscape preferences. If the second parameter is omitted, this method will return the value of the specified preference; otherwise, it sets the value. Netscape only.

    4

    taintEnabled()

    This method returns true if data tainting is enabled; false otherwise.

    Browser Detection

    There is a simple JavaScript which can be used to find out the name of a browser and then accordingly an HTML page can be served to the user.

     Live Demo

    <html>   
       <head>
          <title>Browser Detection Example</title>
       </head>
       
       <body>      
          <script type = "text/javascript">
             <!--
                var userAgent   = navigator.userAgent;
                var opera       = (userAgent.indexOf('Opera') != -1);
                var ie          = (userAgent.indexOf('MSIE') != -1);
                var gecko       = (userAgent.indexOf('Gecko') != -1);
                var netscape    = (userAgent.indexOf('Mozilla') != -1);
                var version     = navigator.appVersion;
                
                if (opera) {
                   document.write("Opera based browser");
                   // Keep your opera specific URL here.
                } else if (gecko) {
                   document.write("Mozilla based browser");
                   // Keep your gecko specific URL here.
                } else if (ie) {
                   document.write("IE based browser");
                   // Keep your IE specific URL here.
                } else if (netscape) {
                   document.write("Netscape based browser");
                   // Keep your Netscape specific URL here.
                } else {
                   document.write("Unknown browser");
                }
                
                // You can include version to along with any above condition.
                document.write("<br /> Browser version info : " + version );
             //-->
          </script>      
       </body>
    </html>

    Output