SlideShare una empresa de Scribd logo
1 de 168
Descargar para leer sin conexión
JScript
    IT1 Course Slide
       Instructor:
     Majid Taghiloo

١
Outline – Part A
• Overview of JavaScript
       i    f        i
    – Versions, embedding, comments
• JavaScript Basics
    – Variables and Data Types
    – Operators
    – Expressions
• JavaScript Control Structures
    – Conditional Statements
    – Looping Statements
2
Introduction
• The growth of the WWW h resulted i a
    h        h f h           has     l d in
  demand for dynamic and interactive web
  sites.
• There are many different kinds of scripting
                 y                       p g
  languages – JavaScript, …
• This lecture aims at offering in‐depth
                                in depth
  knowledge of JavaScript, discussing the
  complexity of scripting and studying various
  common examples.

3
JavaScript Capabilities
• Improve the user interface of a website
• Make your site easier to navigate
• Easily create pop‐up alert, windows
• Replace images on a page without reload the
  p g
  page
• Form validation
• Many others …

4
JavaScript Versions
• J S i 10
  JavaScript 1.0
    – Supported by Netscape 2.0 and IE 3.0
• JavaScript 1.1
    – Supported by Netscape 3.0 and IE 4.0
• JavaScript 1.2
    – Supported by Netscape 4.0 and IE 4.0
• JavaScript 1.3
    – Supported by Netscape 4.5 and IE 5.0
• JavaScript 1.5
    – Supported by Netscape 6.0 and IE 5.5 and later

5
The Future of JavaScript
• ECMA standard brings JavaScript and Jscript together.
    – ECMA ‐ An International industry association dedicated to
      standardize information and communication systems.
• Both Netscape and Microsoft have pledged that they
  will support and develop JavaScript in the future.
• It is future‐proof, and it is not g g to disappear in
               p                    going      pp
  the near future. ☺




6
A Simple Script
<html>
 ht l
<head> <title>First JavaScript Page</title> </head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
<!--
document.write("<hr>");
document.write("Hello World Wide Web");
document.write( <hr> );
document write("<hr>");
-->
</script>
</body>
 /b d
</html>



   7
Embedding JavaScript

    <html>
    <head>
    <title>First JavaScript Program</title>
    </head>
    <body>
    <script language=“JavaScript” src=“your_source_file.js”></script>
            language= JavaScript” src= your_source_file.js”
    </body>
     /b d
    </html>

    • A <script> tag can be placed either within
      the <head> or <body> tag of an HTML
      document.
8
JavaScript Source File

    <script language=“JavaScript”
            language= JavaScript”
    src= your_source_file.js”
    src=“your_source_file.js”></script>

    • SRC – specifies the location of an external script
    • TYPE – specifies the scripting language of the script
              p                p g g g                   p
    • LANGUAGE – specifies the scripting language of the
      script
    • TYPE and LANGUAGE have a similar function, we use
      LANGUAGE to specify the language used in the script

9
Need for a source file
• If the J S i code i f i l short, you are
      h JavaScript d is fairly h
  recommended to include the code in the HTML
  document.
  document
• To add clarity to an HTML document.
• T share J S i code across multiple HTML
  To h     JavaScript d             li l
  documents.
• T h l you hid your J S i code.
  To help      hide      JavaScript d
     – Spent lot of time for JavaScript coding.
     – Vi
       Viewer can only see th l ti of th source fil b t not
                      l      the location f the file but t
       the contents.


10
Hide JavaScript from incompatible
                 browsers
     <script language=“JavaScript”>
              language= JavaScript”
     <!–
     <!– begin hiding JavaScript
     // single-line comment, /* … */ multiple-line comment
         single-    comment,         multiple-
     End hiding JavaScript -->
                g         p -->
     </script>
     <noscript>
      noscript>
     Your b
     Y      browser d
                    does not support J
                                     JavaScript.
                                         S i
     </noscript>
     </noscript>

     • Not all browsers support JavaScript.
     • E g NN1, IE2 character based lynx
       E.g. NN1 IE2, character‐based lynx.
11
JavaScript confusion

           JavaScript                                 Java
Interpreted by the client-side
                   client-             Compiled on the server before
computer                               executed on the client machine
Dynamic binding object references
         binding,                      Static binding object references
                                              binding,
are checked at runtime                 must exist at compile time
No need to declare data types
                         yp            Data types must be declared
                                             yp

Code is embedded in HTML               Code is not integrated in HTML

Limited by the browser functionality   Java applications are standalone

Can access browser objects             Java has no access to browser
                                       objects

  12
Using the alert() Method

     <head>
     <script language=“JavaScript”>
             language= JavaScript”
              alert(“An alert triggered by JavaScript”);
     </script>
           p
     </head>

     • It is the easiest methods to use amongst alert()
                                                   alert(),
       prompt() and confirm().
     • Y can use i to di l textual i f
       You           it display        l information to
                                                  i
       the user (simple and concise).
     • The user can simply click “OK” to close it.
13
Using the confirm() Method

     <head>
     <script language=“JavaScript”>
             language= JavaScript”
              confirm(“Are you happy with the class?”);
     </script>
           p
     </head>

     • This box is used to give the user a choice either
       OK or Cancel.
     • I is very similar to the “ l ()” method.
       It i       i il       h “alert()”    h d
     • You can also put your message in the method.

14
Using the alert() Method

     <head>
     <script language=“JavaScript”>
             language= JavaScript”
              prompt(“What is your student id number?”);
              p
              prompt(“What is your name?”,”No name”);
                  p           y
     </script>
     </head>

     • This is the only one that allows the user to type
       in his own response to the specific question.
     • You can give a default value to avoid displaying
       “undefined”.
15
Three methods

     <script language="JavaScript">
     alert("This is an Alert method");
     confirm("Are you OK?");
     prompt("What is your name?");
     prompt( How
     prompt("How old are you?","20");
                           you? "20");
                                 20 );
     </script>




16
Variables
• J S i allows you to d l
  JavaScript ll        declare and use variables to
                                  d       i bl
  store values.
• H to assign a name to a variable?
  How        i               i bl ?
     – Include uppercase and lowercase letters
     – Digits from 0 through 9
       Di i f         h    h
     – The underscore _ and the dollar sign $
     – No space and punctuation characters
     – First character must be alphabetic letter or underscore –
       99Total?, 012345number?, …
     – Case‐sensitive
     – No reserved words or keywords
                                y

17
Which one is legal?
     My_variable
                            Legal
     $my_variable
        y_
     1my_example
     _my_variable
        y_
     @my_variable
     My_var able_example
     My variable example
     ++my_variable
     ++my_variable
     %my variable
       my_variable           Illegal
     #my_variable
     ~my variable
      my_variable
18
     myVariableExample
Variable on the fly
                         on‐the‐fly

     <head>
     <script language=“JavaScript”>
             language= JavaScript”
                                          Variable declaration
              var id;
              id = prompt(“What is your student id number?”);
                   p     p         y
              alert(id);
              name = prompt(“What is your name?”,”No name”);
              alert(name);
               l (         )
     </script>
     </head>

     • We should use “var” because it is more
       easy to keep track of the variables.
19
Data Types
• J S i allows the same variable to contain diff
  JavaScript ll     h      i bl          i different types
  of data values.
• Primitive data types
     – Number: integer & floating‐point numbers
     – Boolean: logical values “true” or “false”
     – String: a sequence of alphanumeric characters
• Composite data types (or Complex data types)
     – Object: a named collection of data
     – Array: a sequence of values
• Special data types
   p            yp
     – Null: an initial value is assigned
     – Undefined: the variable has been created by not yet assigned a value


20
Numeric Data Types
• It i an i
     is important part of any programming
                          f               i
  language for doing arithmetic calculations.
• JavaScript supports:
     – Integers: A positive or negative number with no
       decimal places.
        • Ranged from –253 to 253
             g
     – Floating‐point numbers: usually written in
       exponential notation.
        • 3.1415…, 2.0e11


21
Integer and Floating‐point number
                  example
     <script language=“JavaScript”>
             language= JavaScript”
            var i t
                integerVar = 100;
                        V     100;
            var floatingPointVar = 3.0e10;
                                        10;
            // fl ti -point number 30000000000
               floating-
               floating i t       b
            document.write(integerVar);
            document.write(integerVar);
            document.write(floatingPointVar)
            document.write(fl
            d                floatingPointVar);
                                     P    V );
     </script>

     • The integer 100 and the number 30,000,000,000
       will be appeared in the browser window.
                pp
22
Boolean Values
• A Boolean value i a l i l value of either
         l       l is logical l        f ih
  true or false. (yes/no, on/off)
• Often used in decision making and data
       p
  comparison.
• In JavaScript, you can use the words “true” and
  “false” directly to indicate Boolean values
   false                               values.
• Named by the 19th century mathematician
  “George Boole”.
  “G        B l ”


23
Boolean value example

     <head>
     <script language=“JavaScript”>
             language= JavaScript”
            var result;
            result = (true*10 + false*7);
                     (true
                     (true*10 false*7
                                false
            alert(“true*10 false*7
            alert(“true*10 + false*7 = “, result);
     </script>
     </head>
     • Th expression i converted t
       The       i is        t d to
        – (1*10 + 0*7) = 10
24
     • They are automatically converted.
Strings
• A string variable can store a sequence of
       i      i bl                        f
  alphanumeric characters, spaces and special
  characters.
• String can also be enclosed in single quotation
       g                            g q
  marks (‘) or in double quotation marks (“).
• What is the data type of “100”?
                             100 ?
     – String but not number type
• P attention to the special characters.
  Pay tt ti t th         i l h     t

25
Strings example

     <head>
     <script language=“JavaScript”>
             language= JavaScript”
              document.write(“This
              document.write(“This is a string.”);
              document.write(“This
              document.write(“This string contains ‘quote’.”);
                                         g          q
              var myString = “My testing string”;
              alert(myString);
              alert(myString);
     </script>
      / i
     </head>

     • Unlike Java and C, JavaScript does not
       have a single character (char) data type.
26
typeof operator

     <head>
     <script language=“JavaScript”>
             language= JavaScript”
              var x = “hello”, y;
              alert(“Variable x value is “ + typeof(x));
                                             typeof(x));
                                              yp
              alert(“Variable y value is “ + typeof(y));
                                             typeof(y));
              alert(“Variable x value is “ + typeof(z));
                                             typeof(z));
     </script>
      / i
     </head>

     • It is an unary operator.
         – Return either: Number, string, Boolean,
                                  ,     g,       ,
           object, function, undefined, null
27
What is an Object?

     • An object is a thing, anything, just as things in
       the real world.
        – E.g. (cars, dogs, money, books, … )
     • In the web browser, objects are the browser
       window itself, forms, buttons, text boxes, …
     • Methods are things that objects can do.
        – Cars can move, dogs can bark.
        – Window object can alert the user “alert()”.
     • All objects have properties
                        properties.
        – Cars have wheels, dogs have fur.
        – Browser has a name and version number.
28
Array
• An Array contains a set of d
                  i          f data represented b
                                               d by
  a single variable name.
• Arrays in JavaScript are represented by the
  Array Object, we need to “new Array()” to
       y j ,                            y()
  construct this object.
• The first element of the array is “Array[0]”
                                      Array[0]
  until the last one Array[i‐1].
• E myArray = new A
  E.g. A               Array(5)
                             (5)
     – We have myArray[0,1,2,3,4].

29
Array Example

     <script language=“JavaScript”>
             language= JavaScript”
              Car = new Array(3);
                         Array(3
              Car[0
              Car[0] = “Ford”;
              Car[1
              Car[1] = “Toyota”;
                          y
              Car[2
              Car[2] = “Honda”;
              document.write(Car[0 “<br>”);
              document.write(Car[0] + “<br>”);
              document.write(Car[1 “<br ”)
              document.write(Car[1] + “<b >”);
              d            i (C [ [1 “ br>”);
              document.write(Car[2 “<br>”);
              document.write(Car[2] + “<br>”);
     </script>
     •   You can also declare arrays with variable length.
          – arrayName = new Array();
          – Length = 0, allows automatic extension of the length.
30
          – Car[9] = “Ford”; Car[99] = “Honda”;
Null & Undefined
• An “ d f d” value is returned when you
      “undefined” l                d h
  attempt to use a variable that has not been
  defined or you have declared but you forgot to
  provide with a value.
• Null refers to “nothing”
• You can declare and define a variable as “null”
                                             null
  if you want absolutely nothing in it, but you
  just don’t want it to be “undefined”.
       don t                undefined


31
Null & Undefined example

     <html>
     <head>
     <title> Null and Undefined example </title>
     <script language=“JavaScript”>
                var test1, test2 = null;
                    test1 test2
                alert(“No value assigned to the variable” + test1);
                                                            test1
                alert(“A null value was assigned” + test2);
                                                    test2
     </script>
            p
     </head>
     <body> … </body>
     </html>
          m




32
JavaScript Special Characters
                      l h

       Character      Meaning
          b         Backspace
                     B k
          f         Form feed
          t       Horizontal tab
          n          New line
          r       Carriage return
                   Backslash
                         k l h
          ’        Single quote
                       g q
33
          ”        Double quote
Operators
•    Arithmetic operators
•    Logical operators
•    Comparison operators
•    String operators
•    Bit wise
     Bit‐wise operators
•    Assignment operators
•    Conditional operators

34
Arithmetic operators

            left_operand “operator” right_operand •

     Operator      Name                  Description            Example
        +         Addition    Adds the operands                  3+5

        -       Subtraction   Subtracts the right operand        5-3
                              from the left operand
        *       Multiplication Multiplies the operands           3*5
        /         Division    Divides the left operand by the    30 / 5
                              right operand
       %          Modulus     Calculates the remainder          20 % 5
35
Unary Arithmetic Operators

     • Binary operators take two operands.
     • Unary type operators take only one operand.
            y yp p                   y      p
     • Which one add value first, and then assign value to the
       variable?



                          Name                 Example
                Post Incrementing operator    Counter++
                Post Decrementing operator     Counter--
                                               Counter--
                 Pre Incrementing operator    ++counter
                                              ++counter
                Pre Decrementing operator      --counter
                                               --counter
36
Logical operators

     • Used to perform Boolean operations on Boolean
       operands



     Operator     Name                 Description             Example
       &&       Logical and   Evaluate to “true” when both
                                           true”               3>2 &&
                              operands are true                 5<2
        ||      Logical or    Evaluate to “true when either   3>1 || 2>5
                              operand is true
        !       Logical not   Evaluate to “true” when the
                                           true”                5 != 3
                              operand is false

37
Comparison operators

           • Used to compare two numerical values
Operator         Name                                 Description                         Example
  ==              Equal          Perform type conversion before checking the              “5” == 5
                                 equality
                                      lit
 ===          Strictly equal     No type conversion before testing                        “5” === 5
  !=           Not equal         “true” when both operands are not equal
                                  true”                                                    4 != 2
  !==       Strictly not equal   No type conversion before testing nonequality            5 !== “5”
   >          Greater than       “true” if left operand is greater than right operand
                                  true”                                                     2>5

   <           Less than         “true” if left operand is less than right operand
                                  true”                                                     3<5

  >=        Greater than or      “true” if left operand is greater than or equal to the
                                  true”                                                    5 >= 2
                equal
                  q              right operand
                                   g     p
  <=          Less than or       “true” if left operand is less than or equal to the
                                  true”                                                    5 <= 2
  38             equal           right operand
Strict Equality Operators

     <script language=“JavaScript”>
      scr pt language JavaScr pt
               var currentWord=“75”;
                   currentWord=“75”;
               var currentValue=75;
                   currentValue=75;
               var outcome1=(currentWord == currentValue)
                   outcome1=(currentWord
                     t       (       tW d      currentValue);
                                                      tV l );
               var outcome2=(currentWord === currentValue);
                   outcome2=(currentWord         currentValue);
               alert(“outcome1
               alert(“outcome1: “ + outcome1 + “ : outcome2: “ + outcome2);
                                    outcome1       outcome2      outcome2
     </script>

     • Surprised that outcome1 is True!
          p
     • JavaScript tries very hard to resolve
       numeric and string differences
                            differences.
39
String operator

     • JavaScript only supports one string
       operator for joining two strings.
     Operator         Name              Description      Return value
         +           String          Joins two strings   “HelloWorld”
                                                          HelloWorld”
                  concatenation


     <script language=“JavaScript”>
               var myString = “”
                      S i     “”;
               myString = “Hello” + “World”;
               alert(myString);
               alert(myString);
                    ( y     g)
                            g)
     </script>
     </script>
40
Bit Manipulation
               Bi M i l i operators
          • Perform operations on the bit representation of
            a value, such as shift left or right
              value                        right.
Operator          Name                                Description
      &        Bitwise AND      Examines each bit position
      |         Bitwise OR      If either bit of the operands is 1, the result will be 1
     ^         Bitwise
               Bit i XOR        Set the
                                S t th result bit only if either bit is 1, b t not b th
                                           lt bit, l       ith       i     but t both
     <<         Bitwise left    Shifts the bits of an expression to the left
                   shift
     >>       Bitwise signed    Shifts the bits to the right, and maintains the sign
                 right shift
     >>>      Bitwise zero-fill Shifts the bits of an expression to right
                       zero-
                 right shift
41
Assignment operators

          • Used to assign values to variables
Operator                            Description                          Example
     =      Assigns the value of the right operand to the left operand    A=2
     +=     Add the operands and assigns the result to the left          A += 5
            operand
     -=     Subtracts the operands and assigns the result to the left    A -= 5
            operand
     *=     Multiplies the operands and assigns the result to the left   A *= 5
            operand d
     /=     Divides the left operands by the right operand and assigns   A /= 5
            the result to the left operand
     %=     Assigns the remainder to the left operand                    A %= 2
42
The most common problem

     <script language=“JavaScript”>
            if ( l h = b t ) { … }
               (alpha beta)
            if (alpha == beta) { … }
     </script>
      / i t

     • Don’t mix the comparison operator and
       Don t
       the assignment operator.
     • double equal sign (==) and the equal
       operator ( )
        p       (=)
43
Order of Precedence
     Precedence              Operator
         1          Parentheses, function calls
         2        , ~, -, ++, --, new, void, delete
                              --,
         3                    *, /
                              * /, %
         4                      +, -
         5                 <<, >>, >>>
         6                 <, <=, >, >=
         7              ==, !=, ===, !==
         8                       &
         9                       ^
        10                        |
        11                      &&
        12                       ||
        13                       ?:
        14              =, +=, -=, *=, …
44
        15           The comma (,) operator
Precedence Example

     Value = (19 % 4) / 1 – 1 - !false
             (19
     Value = 3 / 1 – 1 - !false
     Value = 3 / 1 – 1 - true
     Value = 3 – 1 - true
     Value
     V l =3–2
     Value = 1
45
Scope of a Variable
• When you use a variable i a JavaScript
    h                   i bl in          i
  program that uses functions.
• A global scope variable is one that is declared
  outside a function and is accessible in any part
                                             yp
  of your program.
• A local variable is declared inside a function
  and stops existing when the function ends.



46
Example of variable data types
                        variable,
     <html><head><title> Billing System of Web Shoppe </title></head><body>
     <h1 g
     <h1 align="center"> Billing System of Web Shoppe </h1>
                               g y        f           pp </h1
     <script language="JavaScript">
     firstCustomer = new Array();
     billDetails = new Array(firstCustomer);
                        Array(firstCustomer);
     var custName, custDob, custAddress, custCity, custPhone;
         custName, custDob, custAddress, custCity, custPhone;
     var custAmount, custAmountPaid, custBalAmount;
         custAmount, custAmountPaid, custBalAmount;
     custName=prompt("Enter
     custName=prompt("Enter the first customer's name:", "");
     custDob=prompt("Enter
     custDob=prompt("Enter the first customer's date of birth:", "");
     custAddress=prompt("Enter
     custAddress=prompt("Enter the first customer's address:", "");
     custPhone=prompt("Enter
     custPhone=prompt("Enter the first customer's phone number:", "");
     custAmount=prompt("Enter
     custAmount=prompt("Enter the total bill amount of the first customer:", "");
     custAmountPaid=prompt("Enter
     custAmountPaid=prompt("Enter the amount paid by the first customer:", "");
     custBalAmount = custAmount - custAmountPaid;
                                       custAmountPaid;
     firstCustomer[ ]=custName;
     firstCustomer[0]=custName;
     firstCustomer[ ]=custDob;
     firstCustomer[1]=custDob;
                      ]
     firstCustomer[ ]=custAddress;
     firstCustomer[2]=custAddress;
     firstCustomer[ ]=custPhone;
     firstCustomer[3]=custPhone;
     firstCustomer[ ]=custBalAmount;
     firstCustomer[4]=custBalAmount;
     document.write("<B>"
     document.write("<B>" + "You have entered the following details for first customer:" + "<BR>");
     document.write( Name: " + billDetails[0][0] + "<BR>");
     document.write("Name:
     document write(
                write("Name:      billDetails[ ][0    <BR> );
     document.write("Date
     document.write("Date of Birth: " + billDetails[0][1] + "<BR>");
                                          billDetails[ ][1
     document.write("Address:
     document.write("Address: " + billDetails[0][2] + "<BR>");
                                     billDetails[ ][2
     document.write("Phone:
     document.write("Phone: " + billDetails[0][3] + "<BR>");
                                  billDetails[ ][3
          (custBalAmount == 0) ? document.write("Amount Outstanding: " + custBalAmount):document.write("No amount due")
                                  document.write("Amount                   custBalAmount):document.write("No
     </script></body></html>
      /        /b d /h l


47
Output of the code




48
Conditional Statement
•    “if” statement
•    “if … else” statement
      if else
•    “else if” statement
•    “if/if … else” statement
•    “switch” statement



49
“if” statement
                   if

            if (condition) { statements; }
                condition)
     • It is the main conditional statement in
       JavaScript.
       JavaScript
     • The keyword “if” always appears in lowercase.
     • The condition yields a logical true or false value.
     • The condition is true, statements are executed.



50
“if” statement example
            if

     <script language=“JavaScript”>
     var chr = “”;
     …
     if (chr == ‘A’ || chr == ‘O’) {
        (chr
            document.write(“Vowel
            document.write(“Vowel variable”);
     }
     </script>

              “||” operator ‐ increase the speed of the script


51
“if … else” statement
            if else

          if (condition) { statements; }
              condition)
          else { statements; }

     • You can include an “else” clause in an if
       statement when you want to execute
       some statements if the condition is false.



52
Ternary Sh
            T       Shortcut (
                             (concise)
                                  i )
     <script language=“JavaScript”>
     If (3 > 2) {
         (3
             alert(“True”);
     } else {
             alert(“False”);
     }

     (3 > 2) ? alert(“True”) : alert(“False”);
                l t(“T    ”) l t(“F ls ”)
     </script>

      • Substitute for a simple “if/else” statement.
53
“else if statement
              else if”

          if (condition) { statement; }
              condition)
          else if (condition) { statement; }
                   condition)
          else { statement; }
     • Allows you to test for multiple expression
       for one true value and executes a
       particular bl k of code.
           ti l block f d


54
“if/if else” statement example
          if/if…else

     <script language=“JavaScript”>
     var chr;
          chr;
     chr = prompt(“Please enter a character : “,””);
     if (chr >= ‘A’){
        (chr       ){
            if (chr <= ‘Z’)
               (chr
                    alert( Uppercase );
                    alert(“Uppercase”);
            else if (chr >= ‘a’){
                     (chr
                    alert(“Lowercase”);
                    alert( Lowercase );
            }
     }
55
     </script>
“switch” statement
             switch

          switch (expression) {
                  expression)
                case label1:
                     label
                     l b l1
                          l1
                       statements; break;
                default:
                d f lt
                       statements;
          }

     • Allows you to merge several evaluation
       tests of the same variable into a single
       block f t t
       bl k of statements.
                         t
56
“switch” statement example
            switch

     <script language=“JavaScript”>
     var chr;
         chr;
     chr = prompt(“Pls enter a character in lowercase:”,””);
           prompt(“Pls
     switch(chr){
     switch(chr){
              case ‘a’ :
                         alert(“Vowel a”); break;
              case ‘‘e’’ :
                         alert(“Vowel e”); break;
              default :
                         alert(“Not a vowel”);
     }
     </script>
57
Looping Statement
                         “for” Loops   •
                      “for/in” Loops
                       for/in          •
                      “while” Loops    •
                “do … while” Loops     •
                  “break” statement
                   break               •
              “continue” statement     •



58
“for” statement
                 for

           for (initial_expression; test_exp; change_exp)
                initial_expression; test_exp; change_exp)
           { statements; }
              t t       t

     • One of the most used and familiar loops is the
       for loop.
     • It iterates through a sequence of statements for
       a number of times controlled by a condition.
     • The change exp determines how much has
             change_exp
       been added or subtracted from the counter
       variable.
59
“for” statement example
           for

     <script language=“JavaScript”>
     var counter;
     for (counter = 1; counter <= 10; counter++)
                                  10; counter++)
     {
            document.write(counter*counter
            document.write(counter*counter + “ “);
     }
     </script>

      • Display the square of numbers
      • Output: 1 4 9 16 25 36 49 64 81 100
60
“for/in” statement
                for/in

           for (counter_variable in object)
           { statements; }
              t t     t

     • When the for/in statement is used, the counter
       and termination are determined by the length of
       the object.
              j
     • The statement begins with 0 as the initial value
       of the counter variable, terminates with all the
       properties of the objects have been exhausted.
        – E.g. array   no more elements found

61
“for/in” statement example
           for/in

     <script language=“JavaScript”>
     var b k (Wh t is the difference if “var book=“”;)
         book; (What i th diff               “var b k “” )
     var booklist = new Array(“Chinese”, “English”, “Jap”);
     for (var
     f (var counter i b kli t) {
                   t in booklist
                        booklist)
                                t)
            book += booklist[counter] + “ “;
     }
     alert(book);
     </script>


62
“while” statement
                while

            initial value declaration;
            while (condition) {
              hil condition)
                        diti
                    statements;
                    increment/decrement statement;
                    i        t/d       t t t    t
            }
     • The while loop begins with a termination condition and
       keeps looping until the termination condition is met.
     • The counter variable is managed by the context of the
       statements inside the curly braces.

63
“While” statement example
            While

     <html>
     <head>
     <title>While loop example</title>
     <script language=“JavaScript”>
     var counter = 100;
              t     100;
     var numberlist = “”;
     while (counter > 0) {
          numberlist += “Number “ + counter + “<br>”;
                                              “<br>”;
          counter -= 10;
                     10;
     }
     document.write(numberlist);
     document.write(numberlist);
     </script> <body> … </body>
       /s i t> b d >      /b d >
64
     </html>
“do … while” statement
          do while

          do {
                 statements;
                   t t    t
                 counter increment/decrement;
           } while (t
              hil termination condition)
                       i ti condition)
                                 diti

     • The do/while loop always executes
       statements in the loop in the first iteration
       of the loop
              loop.
     • The termination condition is placed at the
       bottom of the loop.
65
Example of Flow Control




66
Outline – Part B
• JavaScript Functions and Events
         i        i      d
     – Events Handlers
• Using Object in JavaScript
     – Object‐Oriented Programming
       Object Oriented
     – JavaScript Object Model
     – Using Built In objects (Predefined Object)
             Built‐In
     – Custom Object Types
• E
  Error i J S i
        in JavaScript
• Exception Handling in JavaScript
      p               g         p
67
Functions
• Affunction i a bl k of organized reusable
          i is block f         i d       bl
  code (a set of statements) for performing a
  single or related action.
• Begins with keyword “function” and the
     g            y
  function name and “( … )”
• Inside the parentheses
     – We can pass parameters to the function
     – E f ti myfuc(arg1, arg2) { }
       E.g. function f ( 1          2) {…}
     – Built‐in and user‐defined functions

68
Built‐In
                     Built In Functions
• F
  Functions provided b the l
       i         id d by h language and you cannot change
                                          d             h
  them to suit your needs.
• Some of the built‐in functions in JavaScript are shown here:
               built in
     – eval ‐ eval(expr)
         • eval evaluates the expression or statements
     – isFinite
         • Determines if a number is finite
     – isNaN
         • Determines whether a value is “Not a Number”
     – parseInt
         • Converts string literals to integers no number
                                       integers,              NaN.
                                                              NaN
     – parseFloat
         • Finds a floating‐point value at the beginning of a string.


69
User‐Defined
        User Defined Functions
• For some functionality, you cannot achieve by
  only using the built‐in functions.
     y     g
• You can define a function as follows


     function <function_name> (parameters)
               function_name>
     {
         // code segments;
70
     }
Function Declarations

     •   Declaration Syntax
         –   Functions are declared using the function reserved word
                                         g
         –   The return value is not declared, nor are the types of the
             arguments
         –   Examples:
             function square(x) { return(x * x); }
                      square(x)

             function factorial(n) {
                      factorial(n)
                 if (n <= 0) {
                   return(1
                   return(1);
                 } else {
                   return(n * factorial(n - 1));
                 }
             }
71
Events
• Events are the actions that occur as a result of
  browser activities or user interactions with the
  web pages.
     – Such as the user performs an action (mouse click
       or enters data)
     – W can validate th d t entered b a user i a
       We        lid t the data t d by           in
       web form
     – Communicate with Java applets and browser plug‐
       ins

72
Event Categories
• K b d and mouse events
  Keyboard d
     – Capturing a mouse event is simple
• Load events
     d
     – The page first appears on the screen: “Loads”, leaves:
       “Unloads”, …
        Unloads
• Form‐related events
     – onFocus() refers to placing the cursor into the text input in
       the form.
• Others
     – Errors, window resizing.


73
Events defined by JavaScript
HTML elements    HTML      JavaScript                         Description
                 tags    defined events
       Link      <a>         click        Mouse   is clicked on a link
                           dblClick       Mouse   is double-clicked on a link
                                                     double-
                          mouseDown       Mouse   button is pressed
                           mouseUp        Mouse   button is released
                          mouseOver
                                 O        Mouse
                                          M       is moved over a link
                                                  i        d         li k
   Image         <img>       load         Image is loaded into a browser
                             abort        Image loading is abandoned
                             error        An error occurs during the image loading
       Area     <area>    mouseOver       The mouse is moved over an image map area
                          mouseOut        The mouse is moved from image map to outside
                           dblClick       The mouse is double-clicked on an image map
                                                       double-
       Form     <form>      submit        The user submits a form
                             Reset        The user refreshes a form
        …         …           …           …
  74
Event Handlers
• When an event occurs, a code segment i
    h                         d            is
  executed in response to a specific event is
  called “
         “event handler”.
                       ”
• Event handler names are quite similar to the
                            q
  name of events they handle.
• E g the event handler for the “click” event is
  E.g                            click
  “onClick”.

• <HTMLtag eventhandler=“JavaScript Code”>


75
Event Handlers

Event Handlers                         Triggered when
     onChange     The value of the text field, textarea, or a drop down list
                  is modified
      onClick
        Cl k      A l k an image or a form element is clicked once
                    link,             f     l          l k d
     onDblClick   The element is double-clicked
                                 double-
onMouseDown       The user presses the mouse button
      onLoad      A document or an image is loaded
     onSubmit     A user submits a form
      onReset     The form is reset
     onUnLoad     The user closes a document or a frame
     onResize     A form is resized by the user
76
onClick event Handler

     <html>
     <head>
     <title>onClick Event Handler Example</title>
     <script language=“JavaScript”>
          p language= JavaScript”
                g g             p
     function warnUser(){ return confirm(“INE2720 students?”); }
                                   confirm(“INE2720
     </script>
     </head>
      /h d
     <body>
     <a href=“reference html”, onClick=“return warnUser();”>INE2720
        href= reference.html onClick=“return warnUser();”>INE2720
                               onClick=
                                      =                    >INE2720
                                                           >INE
     Students access only</a>
     </body>
     </html>
77
onLoad event Handler

<html>
<head>
<title>onLoad and onUnload Event Handler Example</title>
</head>
<body onLoad=“alert(‘Welcome User’);”
       onLoad=“alert(‘Welcome User’);”
onUnload=“alert(‘Thanks
onUnload=“alert(‘Thanks for visiting the page’);”>
                                         page’);”>
Load and UnLoad event test.
</body>
</html>

 78
User E
              U Events, Form E
                        F    Example
                                  l
     <html><head>
       <title>Simple JavaScript Button</title>
     <script language= JavaScript ><!
              language=“JavaScript"><!--
     function dontClick() {
        alert("I told you not to click!");
     }
     // --></script>
     </head>

     <body>
     <h1>Simple JavaScript Button</h1>
     <form>
      <input type=“button"
           value="Don't Click Me"
           onClick="dontClick()">
     </form>
     </body></html>
79
onMouseOver and onMouseOut Event
                 Handlers

     <html>
     <head>
      h d>
     <title>onMouseOver and onMouseOut event handler</title>
     </head>
      /head
     <body>
     <a href=“link.html”
     onMouseOver = “status = ‘Now mouse is over the link’; “
     onMouseOut = “status = ‘Mouse has moved out’;”>
     A Link Page
     </a>
     </body>
      /body
     </html>
80
Understanding JavaScript Objects

      • One of the most important features of JavaScript,
        enables modular programs.
      • Objects are based on Classes, variables, functions,
        statements are contained in a structure called class.
          Class
                                  varA      varB

                                  varC      varD


                  FunctionA (…)          FunctionB (…)


                  FunctionC ( )
                            (…)          FunctionD ( )
                                                   (…)

81
Class and Object
• You can instantiate an object from a class by using
  the constructor function.
• JavaScript is said to be an Object‐based programming
  language.
• What is property?
     – A variable belongs to the object.
• What is method?
     – It is a function belongs to the object
                                       object.
     – Function‐Valued Properties

82
Creating Instances of Objects
                                 f b
• You can use the “new” operator to create instances of
  objects of a particular class or object type.
     – Variable = new objectType(parameters)
• This objectType() is called constructor.
• E.g. Date is a predefined object type.
     – Assign the current date and time to objA
           g                                 j
        • objA = new Date()
     – Assign another date and time to objB
        • objB = new Date(99,23,5)   23 May, 99



83
Objects and Classes
• Fields Can Be Added On‐the‐Fly
   i ld          dd d     h l
     – Adding a new property (field) is a simple matter
       of assigning a value to one
     – If the field doesn’t already exist when you try to
       assign to it, JavaScript will create it automatically.
     – For instance:

     var test = new Object();
     test.field1
     test field1 = "Value 1"; // Create field1 property
                    Value 1 ;
     test.field2 = 7;         // Create field2 property


84
Objects and Classes – Literal Notation
•    You Can Use Literal Notation
     Y C U Lit l N t ti
     –     You can create objects using a shorthand “literal” notation of the
           form

         { field1:val1, field2:val2, ... , fieldN:valN }

     –     For example, the f ll
                    l h following gives equivalent values to object1 and
                                              l      l                 d
           object2
           var object1 = new Object();
           var object2 = new Object();
           object1.x = 3;
           object1.y = 4;
             j     y
           object1.z = 5;
           object2 = { x:3, y:4, z:5 };



85
Objects and Classes ‐ Constructor

      •       A “Constructor” is Just a Function that Assigns to “this”
          •      JavaScript does not have an exact equivalent to Java s class definition
                                                                  Java’s
          •      The closest you get is when you define a function that assigns values
                 to properties in the this reference
          •      Calling this function using new binds this to a new Object
          •      For example, following is a simple constructor for a Ship class

                 function Ship(x, y, speed, direction) {
                         this.x = x;
                         this.y
                         this y = y;
                         this.speed = speed;
                         this.direction = direction;
                 }
86
Constructor,
       Constructor Example




     var ship1 = new Ship(0, 0, 1, 90);
87
Class Methods Example
             Methods,
     function degreesToRadiansversion of the Ship class that includes a move method
              degreesToRadians(degrees) {
                       Consider a (degrees)                                           •
       return(degrees * Math.PI / 180.0);
                                      180.
     }

     function move() {
       var angle = degreesToRadians(this direction);
                    degreesToRadians(this.direction
                                      this.direction);
                                           direction);
       this.x = this.x + this.speed * Math.cos(angle);
       this.y = this.y + this.speed * Math.sin(angle);
     }

     function Ship(x, y, speed, direction) {
       this.x = x;
       this.y = y;
       this.speed = speed;
       this.direction = direction;
       this.move = move;
        hi
     }
88
Class Methods Result
           Methods,

      var ship1 = new Ship(0, 0, 1, 90);
      ship1.move();
      ship1 move();




89
Objects and Classes ‐ Arrays
•        Arrays
         A
     •      For the most part, you can use arrays in JavaScript a lot like Java arrays.
            •     Here are a few examples:
            var squares = new Array(5);
                                 A     (5)
            for(var i=0; i<squares.length; i++) {
                      vals[i] = i * i;
            }
            // Or, in one fell swoop:
            var squares = new Array(0, 1, 4, 9, 16);
            var array1 = new Array("fee", "fie", "fo", "fum");
            // Literal Array notation for creating an array.
            var array2 = [ "fee", "fie", "fo", "fum" ];
     •      Behind the scenes, however, JavaScript simply represents arrays as objects
            with numbered fields
            •     You can access named fields using either object.field or
                  object["field"], but numbered fields only via object[fieldNumber]



90
Array,
     Array Example



           var arrayObj = new Object();
           arrayObj[0] = "Index zero";
           arrayObj[10] = "Index ten";
           arrayObj.field1
           arrayObj field1 = "Field One";
                              Field One ;
           arrayObj["field2"] = "Field Two";




91
Build‐In J S i Objects
              B ild I JavaScript Obj

Object                                 Description
 Array     Creates new array objects
Boolean    Creates new Boolean objects
                                 j
 Date      Retrieves and manipulates dates and times
 Error     Returns run-time error information
                   run-
Function   Creates new function objects
 Math      Contains methods and properties for performing mathematical
           calculations
             l l ti
Number     Contains methods and properties for manipulating numbers.
 String    Contains methods and properties for manipulating text strings
92
JavaScript References
     http://developer.netscape.com/docs/manuals/communicator/jsref/contents.htm




93
Error and Exception Handling in
                 JavaScript
• While executing your code, runtime
    hil       i          d       i
  exceptions occur.
• How can you write error‐free scripts?
     – The onerror event handler
     – The Error object
        • http://www irt org/xref/Error htm
          http://www.irt.org/xref/Error.htm
     – The throw statement
     – The try … catch … finally block
• Error and Exception are the same.

94
onerror Event Handler
• E
  Errors may occur d t
                   due to
     – syntax errors
        •S
         Syntax i the rules of grammar and spelling
                is h    l    f           d    lli
     – runtime errors
        • The script tries to perform something the system
          (browser) cannot do.
• To capture error event, JavaScript provides the
  onerror event handler.
• The onerror event handler is associated with
  the window object.

95
How to use “onerror” event handler?
                 onerror
      <html>
      <head>
      <title>onerror event handler example /title
      <title>onerror
        title                        example</title>
      <script language=“JavaScript”>
      Function errorHandler(){
                errorHandler(){
          alert( an
          alert(“an error has ocurred”);
                               ocurred”);
                                       );
      }
      window.onerror = errorHandler;
                          errorHandler;
      </script>
      </head>
      <body>
      <script l
            i language=“JavaScript”>
                         “J       i ”
          document.write(“Hello
          document.write(“Hello there;
      </script>
      </body>
96    </html>
Exception Handling in JavaScript

     • An exception is an error generated by the script.
     • Th code that h dl an exception i called an
       The d h handles                  i is ll d
       exception handler that will catch exceptions.


        Normal script flow of control
                   p

                                               The exception is caught
                                                 and handled by an
                                                 exception handler
           If an error is occurred,
        An exception will be thrown.

97
try … catch … finally

     try
     {
        // normal statements
        // might result in an error, throw exceptions
     }
     catch(errorVariable)
     catch(errorVariable)
     {
        // statements that execute in the exception event
     }
     finally
     {
        // After the execution in the catch or try block,
        // the statements in the finally block are executed.
             h              i h fi ll bl k                d
98   }
Try … catch … finally example

<script language=“JavaScript”>
try{
    document.write(“Try
    document.write(“Try block begins” + “<br>”);
                                         “<br>”);
    // create a syntax error
    eval (“10 + * 5”);
         (“10
}catch(errVar){
  catch(errVar){
    document.write( Exception caught
    document write(“Exception caught” + “<br>”);
    document.write(
              write(“Exception           “<br> );
                                          <br>”);
                                          <br>
    document.write(“Error
    document.write(“Error name: “ + errVar.name + “<br>”);
                                                  “<br>”);
    document.write(“Error
    document.write(“Error message: “ + errVar.message + “<br>”);
                                                        “<br>”);
}finally{
  f ll {
    document.write(“Finally
    document.write(“Finally block reached!”);
}
</script>
 99
Outline – Part C
• Working with Browser Objects
      – Document Object Model (DOM)
           • Window, document, history, location Objects
           • Properties and Methods
      –F
       Form V lid ti S i t
            Validation Script
• Creating Cookies in JavaScript
      –   Constructing a standard cookie
      –   Cookie Property
      –   Interaction with the cookie
      –   Using JavaScript to manipulate HTTP cookies

100
Using Browser Objects
• In the previous lectures, you were introduced to
  predefined objects in JavaScript
      – Math, String, Object, Boolean, Date, …
• JavaScript also provides you with objects that can
  control and manipulate the displays of browsers.
      – More dynamic and interactive.
              y
• When a browser loads a webpage, it creates a
  number of JavaScript objects.



101
Document Object Model (DOM)
                    history
• DOM i an object‐oriented model that d
         is    bj       i  d     d l h describes h
                                             ib how
  all elements in an HTML page are arranged.
• I is used to l
  It i      d locate any object i your HTML page (
                          bj in                  (an
  unique address).
• Th
  There are diff
             different DOM l l
                           levels
      –   The Level 0 DOM (DOM0)
      –   The Level
          Th L l 1 DOM (DOM1)
      –   The Level 2 DOM (DOM2)
      –   The Level 3 DOM (DOM3)
           • Under development


102
How the DOM works?

<head><script>
function toggle()
{ document.img.button1.src=“button_on.gif”; }
  document.img.button1
</script></head>                                         reaction
                                   action
<body>
<a href=“test.html” onmouseover=“toggle()”> <img name=“button1” src=“button_off.gif”></a>
   href=“test.html” onmouseover=“toggle()”> <img name=“button1 src=“button_off.gif”></a>
</body>


      Action               Event                JavaScript                 DOM              Reaction
  src=“button_off.gif”   onmouseover               toggle()         document.img.button1    Src=“button_on.gif”


                                                           User moves mouse over object     (١
                                   Event senses that something happened to the object       (٢
                                    JavaScript tells the object what to do (Even handler)   (٣
                                                          Locates object on the web page    (۴
   103                                                   Object’s image source is changed   (۵
Browser Hierarchy Model

                          window



 document         frame            location              history



 anchor          image             form                  link



                          button              checkbox

                          radio                select

                          reset               textarea
                           text                submit
104
The “window” Object
                    window
• It is the highest‐level object in the JavaScript browser
  object hierarchy.
• It is the default object and is created automatically
  when a page is loaded.
• Since it is the default object, we may omit writing
  window e p c y
       do explicitly.
      – document.write(“a test message”);
      – window.document.write(“a test message”);
• It also includes several properties and methods for us
  to manipulate the webpage.
           p               p g
105
Properties and methods of the
              “window” Object
 Property                                Description
  length       An integer value representing the number of frames in the
               window
  name         A string value containing the name of a window
  parent       A string value containing the name of the parent window
  status       A string value representing status bar text

            Method                                Description
           alert(text)           Pop up a window with “text” as the message
                                                       text”
             close()             Closes the current window
            open(url)            Open a new window populated by a URL.
setTimeout(expression, time) Executes an expression after the elapse of
 106                         the interval time.
Example of using the “window” Object
                       window
• Opening and closing windows
• Window attributes of the “open()” method

      Attribute                                 Description
                                                      p
       toolbar      Creates the standard toolbar
       location     Creates the location entry field
      directories   Creates standard directory buttons
        status      Creates the status bar
      menubar       Creates the menu bar at the top of a window
      scrollbars    Creates scrollbars when the document exceeds the window size
      resizable     Enables the user to resize the window
        width       Specifies the width of the window
107
        height      Specifies the height of the window
The “document” Object
              document
  It is one of the important objects in any window or •
                                                frame.
The document object represents a web document or •
                          a page in a browser window.
When you access multiple sites simultaneously, there •
                  would be multiple windows ope ed
                    ou d     u pe        do s opened.
Each window would have a corresponding window object, –
   and each window object would have its own document
                     j
                                                object.


108
Properties and methods of the
                “document” Object
Property                                 Description
 bgColor      A string value representing the background color of a document
alinkColor A string value representing the color for active links
 location     A string value representing the current URL
                     g         p        g
   title      A string value representing the text specified by <title> tag

       Method                                Description
        clear()      Clears the document window
 write(content)
   ite(content)      Writes the text of content to a doc ment
                     W ites     te t                 document
       writeln()     Writes the text and followed by a carriage return
       open()        Open a document to receive data from a write() stream

 109
       close()       Closes a write() stream
The “history” Object
               history
   Each time you visit a web page and click on •
       h i         ii       b         d li k
the “Back” or “Forward” arrow buttons on your
 browser toolbar, you are accessing the history
                                             list.
   You can also add similar buttons / links that •
allow users to move backward and forward via
   the information stored in the history object.



110
Properties and methods of the
              “history” Object
      Property                           Description
       length     An integer value representing the number of links in the
                  history object
      current     Contains the URL of the current page
                                                  p g
       next       Contains the URL of the next entry in the history list
      previous    Contains the URL of the previous entry in the history list

       Method                             Description
       back()      Sends the user to the previous page in the history list
      forward()    Sends the user to the next page in the history list
        go(x)      Sends back or forward by “x” number of pages in the
                   history list
111
The “form” Object
                    form
• The form object is accessed as a property of the
  document object.
• Each form element in a form (text input field, radio
  buttons), is further defined by other objects.
• The browser creates a unique “form” object for each
  form in a docu e
   o        document.
• You can access the form object “form1”
      – document form1
        document.form1



112
Form Element Based Objects
               Element‐Based
• HTML forms can include eight types of input
  elements
      –   Text fields, Textarea fields
      –   Radio buttons
      –   Check box buttons
      –   Hidden fields
      –   Password fields
      –   Combo box select menu
      –   List select menu
      –   Each object has its own properties and methods.

113
Form Validation Script

                                      <html><head>
                                      <html><head>                                                                    <body>
                       <title>Form Example</title>                                                     <h1
                                                                                                       <h1>Form Example</h1>
                                                                                                                Example</h1
                <script LANGUAGE="JavaScript">
                        LANGUAGE= JavaScript >               <p>Enter the following information When you press the Display
                                                                                    information.
                               function validate() {   button, the data you entered will be validated, then sent by email.</p>
if (document.form1.yourname.value.length < 1) {
    (document.form1
             alert("Please enter your full name.");                      <form name="form1" action="mailto:user@host.com"
                                                                               name="form1
                                      return false;                             enctype="text/plain“ onSubmit="validate();">
                                                                                    yp        p                        ();
                                                   }
  if (document.form1.address.value.length < 3) {
     (document.form1                                      <p><b>Name:</b> <input type=“text" length="20" name="yourname">
                                                                                               length="20" name="yourname">
              alert("Please enter your address.");                                                                       </p>
                                      return f ls ;
                                        t n false;       <p><b>Address:</b> <input type=“text" length="30" name="address">
                                                          p b Address /b input type text length="30" name="address">
                                                                                                 length 30 name address
                                                   }                                                                     </p>
     if (document.form1.phone.value.length < 3) {
        (document.form1                                       <p><b>Phone: </b> <input type=“text" length="15" name="phone">
                                                                                                    length="15" name="phone">
        alert("Please enter your phone number.");                                                                        </p>
                                      return f l
                                        t     false;                              <p><input type=“submit" value="Submit"></p>
                                                                                            type= submit value= Submit ></p>
                                                   }
                                       return true;                                                                   </form>
                                                   }                                                                  </body>
                                          </script>
                                            /                                                                         </html>
                                            </head>
  114
Application: Using JavaScript to Validate CGI
                         Forms
1.
1      Accessing F
       A     i Forms
      –    The document.forms property contains an array of Form entries
           contained in the document
      –    As usual in JavaScript, named entries can be accessed via name
           instead of by number, plus named forms are automatically inserted
           as properties in the document object, so any of the following
              p p                           j ,        y               g
           formats would be legal to access forms

          var fi tF m = d
              firstForm document.forms[0];
                              m t f m [0];
          // Assumes <FORM NAME="orders" ...>
          var orderForm = document.forms["orders"];
                    F m       um n .f m [          ];
          // Assumes <FORM NAME="register" ...>
          var registrationForm = document.register;

115
Application: Using JavaScript to Validate CGI
                      Forms, cont.
2.     Accessing Elements within Forms
      –   The Form object contains an elements property that holds an array
          of Element objects
      –   You can retrieve form elements by number, by name from the array,
          or via the property name:


 var firstElement = firstForm.elements[0];
 // Assumes <INPUT ... NAME="quantity">
                             E "       "
 var quantityField = orderForm.elements["quantity"];
 // Assumes <INPUT ... NAME= submitSchedule >
                        NAME="submitSchedule">
 var submitButton = register.submitSchedule;


116
Checking Form Values Individually,
                  Example
      <html><head><title>On-Line Training</title>
      <script language=“JavaScript">
      <!--
      // Wh
         When the user changes and leaves t tfi ld check
                th        h         d l      textfield, h k
      // that a valid choice was entered. If not, alert
      // user, clear field, and set focus back there.

      function checkLanguage() {
        // or document.forms["langForm"].elements["langField"]
        var field = document.langForm.langField;
        var lang = field.value;
        var prefix = lang.substring(0, 4).toUpperCase();
        if (prefix != "JAVA") {
          alert("Sorry, '" + lang + "' is not valid.n" +
                "Please try again ");
                 Please     again. );
          field.value = ""; // Erase old value
          field.focus();    // Give keyboard focus
        }
      }

117
Checking Form Values Individually,
                Example, cont.
      // -->
      </script></head>
      <body><h1>On-Line Training</h1>
           y                     g
      <form action="cgi-bin/registerLanguage" name="langForm">
      To see an introduction to any of our on-line training
      courses, please enter the name of an important Web
      programming language below.
      <p>
      <b>Language:</b>
      <input type=“text" name="langField"
             onFocus="describeLanguage()" onBlur="clearStatus()"
             onChange="checkLanguage()">
      <p>
      <input type=“submit" value="Show It To Me">
      </form>
      </body>
      </html>
118
Checking Form Values Individually,
                  Results




119
Checking Values When Form is Submitted,
                Example
      <html><head><title>Camp Registration</title>
      <script language=“JavaScript">
      <!--
        !
      function isInt(string) {
          var val = parseInt(string);
          return(val > 0);
      }
      function checkRegistration() {
          var ageField = document.registerForm.ageField;
          if (!isInt(ageField.value)) {
            alert("Age must be an integer.");
            return(false);
          }
          ...
          // Format looks OK. Submit form.
          return(true);
      }
      // -->
120
      </script>
Checking Values When Form is Submitted,
             Example, cont.
      <body><h1>Camp Registration</h1>
      <form action="cgi-bin/register“ name="registerForm"
           onSubmit="return(checkRegistration())">
                            (        g       ())

      Age: <input type=“text" name="ageField" onFocus="promptAge()"
                onBlur="clearStatus()"><br>

      Rank: <input type=“text" name="rankField" onFocus="promptRank()"
                 onBlur="clearStatus()"><br>

      Serial Number: <input type=“text" name="serialField"
         onFocus="promptSerial()" onBlur="clearStatus()"><p>

      <input type=“submit" value="Submit Registration">
      </form>
      </body>
      </html>
       /ht l

121
Checking Values When Form is Submitted,
                Results




122
Why we need Cookies?
• The web servers process requests efficiently because
  they did not need to maintain any unique
  requirements for different clients.
• Web browsers treat every visit to a web page as an
  entirely new session, even if users open a different
  web page on the same server.
• The client information becomes more important for
  commercial purposes.
               p p



123
Cookie Basics
• When a user closes the browser, the information
  contained in a hidden form field will be lost.
• A cookie is used to store information on the user’s
  computer even when the user switches off his/her
  computer.
• It is a da a that is se from a web se e to a web
      s data a s sent o           eb server o      eb
  browser when the user visits a site on a server.
      – It is just a .txt file in a user’s computer.
                                    user s



124
Features of Cookies
• A cookie can b associated with one or more
         ki    be      i d ih
  documents on the web server.
• More than one cookie can be associated with
  a document on the web server.
• Every cookie has a NAME‐VALUE pair
  associated with it
                  it.
• Cookies have an expiration date associated
  with th
    ith them.


125
Cookies Applications
•     Web page customization for each user
•     Form information storage
•     Shopping carts for order information
•     Store userID and password
•     Track how many times the user has visited
•     Maintain a past score for each player on a test or
      online games



126
Application: Using JavaScript to Store and
                   Examine Cookies
1. Using document.cookies
      – Set it (one cookie at a time) to store values
               (                    )
      document.cookie = "name1=val1";
      document.cookie
      document cookie = "name2=val2; expires=" + someDate;
                         name2 val2; expires
      document.cookie = "name3=val3; path=/; domain=test.com";


      – Read it (all cookies in a single string) to access
        values



127
Application: Using JavaScript to Store and
                   Examine Cookies
2.
2     Parsing Cookies
      P i C ki
function cookieVal(cookieName, cookieString) {
  var startLoc = cookieString indexOf(cookieName);
                 cookieString.indexOf(cookieName);
  if (startLoc == -1) {
    return(""); // No such cookie
  }
  var sepLoc = cookieString.indexOf("=", startLoc);
  var endLoc = cookieString.indexOf(";", startLoc);
  if (endLoc == -1) { // Last one has no ";"
    endLoc = cookieString.length;
  }
  return(cookieString.substring(sepLoc+1, endLoc));
}


128
Cookie,
                      Cookie Example
      <html><head>
          <title>Widgets "R" Us</title>
      <script language=“JavaScript">
      <!--
        !
      function storeCookies() {
          var expires = "; expires=Monday, 01-Dec-02 23:59:59 GMT";
          var first = document widgetForm firstField value;
                      document.widgetForm.firstField.value;
          var last = document.widgetForm.lastField.value;
          var account = document.widgetForm.accountField.value;
          document.cookie = "first=" + first + expires;
          document.cookie = "last=" + last + expires;
          document.cookie = "account=" + account + expires;
      }

      // Store cookies and give user confirmation.
      function registerAccount() {
        storeCookies();
                     ()
        alert("Registration Successful.");
      }
129
Cookie, Example, cont.
                Cookie Example cont
      f
      function cookieVal(cookieName, cookieString) {
                         (         m ,           g)
        var startLoc = cookieString.indexOf(cookieName);
        if (startLoc == -1) {
          return(""); // No such cookie
        }
        var sepLoc = cookieString.indexOf("=", startLoc);
        var endLoc = cookieString.indexOf(";", startLoc);
        if (endLoc == -1) { // Last one has no ";"
          endLoc = cookieString length;
                    cookieString.length;
        }
        return(cookieString.substring(sepLoc+1, endLoc));
      }

      function presetValues() {
        var firstField = document.widgetForm.firstField;
        var lastField = document.widgetForm.lastField;
        var accountField = document widgetForm accountField;
                            document.widgetForm.accountField;
        var cookies = document.cookie;
        firstField.value = cookieVal("first", cookies);
        lastField.value = cookieVal("last", cookies);
        accountField.value cookieVal( account
        accountField value = cookieVal("account", cookies);
      }
      // --></script></head>
130
Cookie, Example, cont.
                Cookie Example cont
      <body onLoad="presetValues()">
            onLoad= presetValues() >
      <h1>Widgets "R" Us</h1>

      <form action="servlet/cwp.Widgets" name="widgetForm"
       f      ti   "    l t/    Wid t "       " id tF    "
         onSubmit="storeCookies()">

      First Name: <input type=“text" name="firstField"><br>
      F      N                 “    "       "f   F ld" b
      Last Name: <input type=“text" name="lastField"><br>
      Account Number: <input type=“text" name="accountField"><br>
      Widget Name: <input type=“text" name="widgetField"><br>
      <input type=“button" value="Register Account" onClick="registerAccount()">
      <input type=“submit" value="Submit Order
        input type submit value Submit Order">

      </form>
      </body>
      </html>
131
Cookie, Example,
      Cookie Example Result




132
Outline – Part D
• I t d i DHTML
  Introducing
      – Styles and Layers
      – Dynamic Positioning
      – Moving objects in 3D
      – Internet Explorer Filters
                    l      il
•     Using DHTML and CSS Tools
•     Cool JavaScript Sites
•     JavaScript and DHTML Reference
              p
•     Summary

133
Dynamic HTML
• Everyone is a Web Designer.
      – Learning DHTML, CSS and JavaScript is your next step into
        the web design world.
• “DHTML” is a term used by some vendors to describe
  the combination of HTML, style sheets and scripts
  that allows documents to be animated.
• Web pages can be made to respond to users’ actions.
• Problem: How to achieve “Dynamic”?
                           Dynamic ?


134
DHTML advantages / disadvantages
• Supported b most b
            d by        browsers
• Small file sizes (faster than Flash)
                   (                 )
• No plug‐ins required
• Easy to learn (learn HTML, JavaScript)
                        HTML
• Faster web experience (change the page
  content without l
               h     load new pages) )
• Browser and OS incompatibilities
                            p
      – The implementation of CSS, DOM varies from
        browser to browser
135
What makes a web site dynamic?
• I
  Interactivity – adapt and react to the visitor’s actions
           i i     d       d           h ii ’           i
  as quick as possible.
• S h i i – b i together relevant i f
  Synchronicity bring          h     l       information
                                                       i
  from a variety of sources.
• Fl ibili – give the visitor diff
  Flexibility i h i i different ways to fi d      find
  information in the site.
• Ad
  Adaptability – adjusts to cater to i di id l visitor’s
          bili     dj                 individual i i ’
  needs.
• A i i – uses motion and sound to d
  Activity            i      d      d draw user’s    ’
  attention to changes on the site.

136
The Role of each component in DHTML
• With CSS, we can change the style of any
    ih               h       h    l f
  HTML elements.
• With DOM, we can have a map on every
  elements in the HTML page.
                         p g
• With JavaScript, we can access and have
  operations on the elements in the DOM tree
                                          tree.
• With event handler, we can execute the
  predefined scripts at any ti
     d fi d i t t           time.


137
Cross‐Browser
            Cross Browser DHTML

Netscape 4.x    Cross-Browser
                Cross-            Internet Explorer
                DHTML             4.x
 JavaScript      CSS1 CSS2
                 CSS1, CSS2,       Visual Filters
Style Sheets    CSS-
                CSS-Positioning   allow you to apply
(JSS)            JavaScript
                         p        visual effects to
 Netscape        DOM              text or graphics
Layers
   y                               Data Binding g
(positioning,
visibility)
         y)
  138
Open a new browser window
• Pop‐up windows are useful for navigation
                              pp
  controls, advertisements, supplementaryy
  contents.
• You can open a window close the window or
                  window,          window,
  toggle the window.




139
Dynamic Technique:
               Change CSS Styles

      • You can change or add to any CSS property
        defined for
        d fi d f any object on the screen.
                        bj        h




                          onMouseOver()




140
Change Background Color
<html><head>
<script language="JavaScript">
function bgChange(bg)
{     document.body.style.background=bg; }
</script></head>
<body><b>Mouse over these table cells, and the background color will change</b>
<table width="300" height="100">
 <tr>
  <td onmouseover="bgChange('red')"
      onmouseout="bgChange('transparent')" bgcolor="red">
  </td>
  <td onmouseover="bgChange('blue')"
      onmouseout="bgChange('transparent')" bgcolor="blue">
  </td>
  <td onmouseover="bgChange('green')"
      onmouseout="bgChange('transparent')” bgcolor="green">
  </td>
</tr>
</table>
</body></html>

    141
CSS Properties




      Reference: http://www.library.utoronto.ca/HTMLcourses/DHTML/properties1.html   •
142
Dynamic Positioning

      • It means the HTML elements can be
        positioned by using JavaScript
                              JavaScript.
      • The element is moved by manipulating
        any of the “top”, “left”, “right” and
                    top left right
        “bottom” CSS properties.
      • The more table you use the slower your
                              use,
        page displays.
      • Positioning elements with CSS is more
        accurate than tables and the results are
        displayed much faster
                         faster.
143
Moving Objects from Point to Point

      • Using CSS, you can change the position of
        an object on the screen.
            bj        h




144
Moving Objects in 3 D
                             3‐D

      • By specifying the z‐index, we can put the
        objects i 3 D manner.
         bj t in 3‐D




145
Moving the browser window

      • You can set an initial position of multiple windows.




146
IE DHTML Visual Controls

      • The blurOn() Filter causes the image to
        blur
        bl on th screen.
               the




147
IE Transition Filters

      • Produce transitions between web pages.

                                 Transition        Reference #
                                 Box In            0
                                 Box Out           1
                                 Circle out        3
                                 Wipe up           4
                                 Wipe down         5
                                 Wipe right
                                 Wi    i ht        6
                                 Wipe left         7
                                 Random Dissolve   12
                                 Random            23
148
Adding last modified Date

<html>
<head>
<title>Enter the title of your HTML document here</title>
</head>
<body>
<script language=“JavaScript”>
document.write( Page
document write(“Page last modified: “ + document lastModified)
                                        document.lastModified)
</script>
</body>
</html>



  149
Creating a Sliding Menu

      • Allow visitors to pull out menus or put them away.




150
Follow the Mouse Pointer
• The mouse pointer is part of the user interface
  that gives designer controls.
       g         g




151
Application: Using JavaScript to Make Pages
                       Dynamic
•      Modifying Images Dynamically
      – The document.images property contains an
                               g p p y
        array of Image objects corresponding to each
        IMG element in the current document
      – To display a new image, simply set the SRC
        property of an existing image to a string
        representing a different image file




152
Modifying Images Example
                    Images,
• Th f ll i f
  The following function changes the fi i
                     i    h       h first image i a d
                                                in document
      function changeImage() {
          document.images[0].src = "images/new-image.gif";
      }

• Referring to images by name is easier:
      <img src="cool-image.jpg" name="cool"
        im      "   l im    jp " n m "     l"
      width=75 height=25>
      function improveImage() {
           document.images["cool"].src = "way-cool.jpg";
      }


153
Modifying Images: A Clickable Image Button,
                      Example

       <script language=“JavaScript">
       <!--
       imageFiles = new Array("images/Button1-Up gif",
                         Array( images/Button1-Up.gif
                           "images/Button1-Down.gif",
                           "images/Button2-Up.gif",
                           "images/Button2-Down gif");
                            images/Button2-Down.gif );
       imageObjects = new Array(imageFiles.length);
       for(var i=0; i<imageFiles.length; i++) {
         imageObjects[i] = new Image(150 25);
                                Image(150,
         imageObjects[i].src = imageFiles[i];
       }

       function setImage(name, image) {
         document.images[name].src = image;
       }

154
Modifying Images: A Clickable Image Button,
                      Example
function clickButton(name grayImage) {
           clickButton(name,
   var origImage = document.images[name].src;
   setImage(name, grayImage);
   var resetString =
     "setImage('" + name + "' '" + origImage + "')"
     " tI       ('"        "',       i I       "')";
   setTimeout(resetString, 100);
}
// --></script>
              p
</head>...
<a href="location1.html"
    onMouseOver="clickButton('Button1', 'images/Button1-Down.gif')">
<img src="images/Button1-Up.gif" name="Button1"
  img src images/Button1 Up.gif name Button1
      width=150 height=25></A>
<a href="location2.html"
    onMouseOver="clickButton('Button2', 'images/Button2-Down.gif')">
<img src="images/Button2 Up gif" name= Button2
       src= images/Button2-Up.gif name="Button2"
      width=150 height=25></A>
...



155
Highlighting Images Under the Mouse,
                     Example
<html>
 ht l>
<head> <title>High Peaks Navigation Bar</title>

<script language=“JavaScript">
<!—
// Given "Foo", returns "images/Foo.gif".
           Foo ,         images/Foo.gif .
function regularImageFile(imageName) {
  return("images/" + imageName + ".gif");
}
// Given "Bar", returns "images/Bar-Negative.gif".
function negativeImageFile(imageName) {
  return("images/" + imageName + "-Negative.gif");
}


156
Highlighting Images Under the Mouse,
                  Example, cont.

 // Cache image at specified index. E.g., given index 0,
 // take imageNames[0] to get "Home". Then preload
 // images/Home.gif and images/Home-Negative.gif.
 function cacheImages(index) {
   regularImageObjects[index] = new Image(150, 25);
   regularImageObjects[index].src = regularImageFile(imageNames[index]);
   negativeImageObjects[index] = new Image(150, 25);
   negativeImageObjects[index].src = negativeImageFile(imageNames[index]);
 }
 imageNames = new Array("Home", "Tibet", "Nepal", "Austria", "Switzerland");
 regularImageObjects = new Array(imageNames.length);
 negativeImageObjects = new Array(imageNames.length);
 // Put images in cache for fast highlighting.
 for(var i=0; i<imageNames.length; i++) {
   cacheImages(i);
 }
157
Highlighting Images Under the Mouse,
                  Example, cont.
...
function highlight(imageName) {
  document.images[imageName].src = negativeImageFile(imageName);
}

function unHighlight(imageName) {
  document.images[imageName].src = regularImageFile(imageName);
}
// -->
</script></head>
<body>
<table>
 <tr><td><a href="Tibet.html" target="Main"
         onMouseOver="highlight('Tibet')" onMouseOut="unHighlight('Tibet')">
         <img src="images/Tibet.gif" name="Tibet“ width=150 height=25 border=0>
       </a>
...
158
Lecture7
Lecture7
Lecture7
Lecture7
Lecture7
Lecture7
Lecture7
Lecture7
Lecture7
Lecture7

Más contenido relacionado

La actualidad más candente (20)

An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScript
 
Java script
Java scriptJava script
Java script
 
Javascript
JavascriptJavascript
Javascript
 
Java script
Java scriptJava script
Java script
 
70 536
70 53670 536
70 536
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Os Borger
Os BorgerOs Borger
Os Borger
 
Placement and variable 03 (js)
Placement and variable 03 (js)Placement and variable 03 (js)
Placement and variable 03 (js)
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Java Script An Introduction By HWA
Java Script An Introduction By HWAJava Script An Introduction By HWA
Java Script An Introduction By HWA
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Web programming
Web programmingWeb programming
Web programming
 
Javascript
JavascriptJavascript
Javascript
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 
Generics
GenericsGenerics
Generics
 
Javascript by geetanjali
Javascript by geetanjaliJavascript by geetanjali
Javascript by geetanjali
 
Javascript tutorial
Javascript tutorialJavascript tutorial
Javascript tutorial
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
Javascript Roadmap - The Basics
Javascript Roadmap - The BasicsJavascript Roadmap - The Basics
Javascript Roadmap - The Basics
 
Javascript
JavascriptJavascript
Javascript
 

Destacado (7)

Lecture5
Lecture5Lecture5
Lecture5
 
Lecture2
Lecture2Lecture2
Lecture2
 
Lecture8
Lecture8Lecture8
Lecture8
 
Lecture6
Lecture6Lecture6
Lecture6
 
Lecture1
Lecture1Lecture1
Lecture1
 
Lecture3
Lecture3Lecture3
Lecture3
 
Resume modifikasi daun dan filotaksis
Resume modifikasi daun dan filotaksisResume modifikasi daun dan filotaksis
Resume modifikasi daun dan filotaksis
 

Similar a Lecture7

Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptxAlkanthiSomesh
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxTusharTikia
 
Malicious Intent: Adventures in JavaScript Obfuscation and Deobfuscation
Malicious Intent: Adventures in JavaScript Obfuscation and DeobfuscationMalicious Intent: Adventures in JavaScript Obfuscation and Deobfuscation
Malicious Intent: Adventures in JavaScript Obfuscation and DeobfuscationHeadlessZeke
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scriptingpkaviya
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScriptDan Phiffer
 
JavaScript : A trending scripting language
JavaScript : A trending scripting languageJavaScript : A trending scripting language
JavaScript : A trending scripting languageAbhayDhupar
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMegha V
 
javascriptPresentation.pdf
javascriptPresentation.pdfjavascriptPresentation.pdf
javascriptPresentation.pdfwildcat9335
 
Lect-5--JavaScript-Intro-12032024-105816am.pptx
Lect-5--JavaScript-Intro-12032024-105816am.pptxLect-5--JavaScript-Intro-12032024-105816am.pptx
Lect-5--JavaScript-Intro-12032024-105816am.pptxzainm7032
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxrish15r890
 
JavaScript
JavaScriptJavaScript
JavaScriptBIT DURG
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMarlon Jamera
 
Java Script basics and DOM
Java Script basics and DOMJava Script basics and DOM
Java Script basics and DOMSukrit Gupta
 

Similar a Lecture7 (20)

Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptx
 
Java script
Java scriptJava script
Java script
 
Malicious Intent: Adventures in JavaScript Obfuscation and Deobfuscation
Malicious Intent: Adventures in JavaScript Obfuscation and DeobfuscationMalicious Intent: Adventures in JavaScript Obfuscation and Deobfuscation
Malicious Intent: Adventures in JavaScript Obfuscation and Deobfuscation
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
JavaScript : A trending scripting language
JavaScript : A trending scripting languageJavaScript : A trending scripting language
JavaScript : A trending scripting language
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Java scipt
Java sciptJava scipt
Java scipt
 
javascriptPresentation.pdf
javascriptPresentation.pdfjavascriptPresentation.pdf
javascriptPresentation.pdf
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
Lect-5--JavaScript-Intro-12032024-105816am.pptx
Lect-5--JavaScript-Intro-12032024-105816am.pptxLect-5--JavaScript-Intro-12032024-105816am.pptx
Lect-5--JavaScript-Intro-12032024-105816am.pptx
 
Java script core
Java script coreJava script core
Java script core
 
JavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptxJavaScript New Tutorial Class XI and XII.pptx
JavaScript New Tutorial Class XI and XII.pptx
 
Lecture 5 javascript
Lecture 5 javascriptLecture 5 javascript
Lecture 5 javascript
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
JavaScript Basics with baby steps
JavaScript Basics with baby stepsJavaScript Basics with baby steps
JavaScript Basics with baby steps
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Java Script basics and DOM
Java Script basics and DOMJava Script basics and DOM
Java Script basics and DOM
 

Lecture7

  • 1. JScript IT1 Course Slide Instructor: Majid Taghiloo ١
  • 2. Outline – Part A • Overview of JavaScript i f i – Versions, embedding, comments • JavaScript Basics – Variables and Data Types – Operators – Expressions • JavaScript Control Structures – Conditional Statements – Looping Statements 2
  • 3. Introduction • The growth of the WWW h resulted i a h h f h has l d in demand for dynamic and interactive web sites. • There are many different kinds of scripting y p g languages – JavaScript, … • This lecture aims at offering in‐depth in depth knowledge of JavaScript, discussing the complexity of scripting and studying various common examples. 3
  • 4. JavaScript Capabilities • Improve the user interface of a website • Make your site easier to navigate • Easily create pop‐up alert, windows • Replace images on a page without reload the p g page • Form validation • Many others … 4
  • 5. JavaScript Versions • J S i 10 JavaScript 1.0 – Supported by Netscape 2.0 and IE 3.0 • JavaScript 1.1 – Supported by Netscape 3.0 and IE 4.0 • JavaScript 1.2 – Supported by Netscape 4.0 and IE 4.0 • JavaScript 1.3 – Supported by Netscape 4.5 and IE 5.0 • JavaScript 1.5 – Supported by Netscape 6.0 and IE 5.5 and later 5
  • 6. The Future of JavaScript • ECMA standard brings JavaScript and Jscript together. – ECMA ‐ An International industry association dedicated to standardize information and communication systems. • Both Netscape and Microsoft have pledged that they will support and develop JavaScript in the future. • It is future‐proof, and it is not g g to disappear in p going pp the near future. ☺ 6
  • 7. A Simple Script <html> ht l <head> <title>First JavaScript Page</title> </head> <body> <h1>First JavaScript Page</h1> <script type="text/javascript"> <!-- document.write("<hr>"); document.write("Hello World Wide Web"); document.write( <hr> ); document write("<hr>"); --> </script> </body> /b d </html> 7
  • 8. Embedding JavaScript <html> <head> <title>First JavaScript Program</title> </head> <body> <script language=“JavaScript” src=“your_source_file.js”></script> language= JavaScript” src= your_source_file.js” </body> /b d </html> • A <script> tag can be placed either within the <head> or <body> tag of an HTML document. 8
  • 9. JavaScript Source File <script language=“JavaScript” language= JavaScript” src= your_source_file.js” src=“your_source_file.js”></script> • SRC – specifies the location of an external script • TYPE – specifies the scripting language of the script p p g g g p • LANGUAGE – specifies the scripting language of the script • TYPE and LANGUAGE have a similar function, we use LANGUAGE to specify the language used in the script 9
  • 10. Need for a source file • If the J S i code i f i l short, you are h JavaScript d is fairly h recommended to include the code in the HTML document. document • To add clarity to an HTML document. • T share J S i code across multiple HTML To h JavaScript d li l documents. • T h l you hid your J S i code. To help hide JavaScript d – Spent lot of time for JavaScript coding. – Vi Viewer can only see th l ti of th source fil b t not l the location f the file but t the contents. 10
  • 11. Hide JavaScript from incompatible browsers <script language=“JavaScript”> language= JavaScript” <!– <!– begin hiding JavaScript // single-line comment, /* … */ multiple-line comment single- comment, multiple- End hiding JavaScript --> g p --> </script> <noscript> noscript> Your b Y browser d does not support J JavaScript. S i </noscript> </noscript> • Not all browsers support JavaScript. • E g NN1, IE2 character based lynx E.g. NN1 IE2, character‐based lynx. 11
  • 12. JavaScript confusion JavaScript Java Interpreted by the client-side client- Compiled on the server before computer executed on the client machine Dynamic binding object references binding, Static binding object references binding, are checked at runtime must exist at compile time No need to declare data types yp Data types must be declared yp Code is embedded in HTML Code is not integrated in HTML Limited by the browser functionality Java applications are standalone Can access browser objects Java has no access to browser objects 12
  • 13. Using the alert() Method <head> <script language=“JavaScript”> language= JavaScript” alert(“An alert triggered by JavaScript”); </script> p </head> • It is the easiest methods to use amongst alert() alert(), prompt() and confirm(). • Y can use i to di l textual i f You it display l information to i the user (simple and concise). • The user can simply click “OK” to close it. 13
  • 14. Using the confirm() Method <head> <script language=“JavaScript”> language= JavaScript” confirm(“Are you happy with the class?”); </script> p </head> • This box is used to give the user a choice either OK or Cancel. • I is very similar to the “ l ()” method. It i i il h “alert()” h d • You can also put your message in the method. 14
  • 15. Using the alert() Method <head> <script language=“JavaScript”> language= JavaScript” prompt(“What is your student id number?”); p prompt(“What is your name?”,”No name”); p y </script> </head> • This is the only one that allows the user to type in his own response to the specific question. • You can give a default value to avoid displaying “undefined”. 15
  • 16. Three methods <script language="JavaScript"> alert("This is an Alert method"); confirm("Are you OK?"); prompt("What is your name?"); prompt( How prompt("How old are you?","20"); you? "20"); 20 ); </script> 16
  • 17. Variables • J S i allows you to d l JavaScript ll declare and use variables to d i bl store values. • H to assign a name to a variable? How i i bl ? – Include uppercase and lowercase letters – Digits from 0 through 9 Di i f h h – The underscore _ and the dollar sign $ – No space and punctuation characters – First character must be alphabetic letter or underscore – 99Total?, 012345number?, … – Case‐sensitive – No reserved words or keywords y 17
  • 18. Which one is legal? My_variable Legal $my_variable y_ 1my_example _my_variable y_ @my_variable My_var able_example My variable example ++my_variable ++my_variable %my variable my_variable Illegal #my_variable ~my variable my_variable 18 myVariableExample
  • 19. Variable on the fly on‐the‐fly <head> <script language=“JavaScript”> language= JavaScript” Variable declaration var id; id = prompt(“What is your student id number?”); p p y alert(id); name = prompt(“What is your name?”,”No name”); alert(name); l ( ) </script> </head> • We should use “var” because it is more easy to keep track of the variables. 19
  • 20. Data Types • J S i allows the same variable to contain diff JavaScript ll h i bl i different types of data values. • Primitive data types – Number: integer & floating‐point numbers – Boolean: logical values “true” or “false” – String: a sequence of alphanumeric characters • Composite data types (or Complex data types) – Object: a named collection of data – Array: a sequence of values • Special data types p yp – Null: an initial value is assigned – Undefined: the variable has been created by not yet assigned a value 20
  • 21. Numeric Data Types • It i an i is important part of any programming f i language for doing arithmetic calculations. • JavaScript supports: – Integers: A positive or negative number with no decimal places. • Ranged from –253 to 253 g – Floating‐point numbers: usually written in exponential notation. • 3.1415…, 2.0e11 21
  • 22. Integer and Floating‐point number example <script language=“JavaScript”> language= JavaScript” var i t integerVar = 100; V 100; var floatingPointVar = 3.0e10; 10; // fl ti -point number 30000000000 floating- floating i t b document.write(integerVar); document.write(integerVar); document.write(floatingPointVar) document.write(fl d floatingPointVar); P V ); </script> • The integer 100 and the number 30,000,000,000 will be appeared in the browser window. pp 22
  • 23. Boolean Values • A Boolean value i a l i l value of either l l is logical l f ih true or false. (yes/no, on/off) • Often used in decision making and data p comparison. • In JavaScript, you can use the words “true” and “false” directly to indicate Boolean values false values. • Named by the 19th century mathematician “George Boole”. “G B l ” 23
  • 24. Boolean value example <head> <script language=“JavaScript”> language= JavaScript” var result; result = (true*10 + false*7); (true (true*10 false*7 false alert(“true*10 false*7 alert(“true*10 + false*7 = “, result); </script> </head> • Th expression i converted t The i is t d to – (1*10 + 0*7) = 10 24 • They are automatically converted.
  • 25. Strings • A string variable can store a sequence of i i bl f alphanumeric characters, spaces and special characters. • String can also be enclosed in single quotation g g q marks (‘) or in double quotation marks (“). • What is the data type of “100”? 100 ? – String but not number type • P attention to the special characters. Pay tt ti t th i l h t 25
  • 26. Strings example <head> <script language=“JavaScript”> language= JavaScript” document.write(“This document.write(“This is a string.”); document.write(“This document.write(“This string contains ‘quote’.”); g q var myString = “My testing string”; alert(myString); alert(myString); </script> / i </head> • Unlike Java and C, JavaScript does not have a single character (char) data type. 26
  • 27. typeof operator <head> <script language=“JavaScript”> language= JavaScript” var x = “hello”, y; alert(“Variable x value is “ + typeof(x)); typeof(x)); yp alert(“Variable y value is “ + typeof(y)); typeof(y)); alert(“Variable x value is “ + typeof(z)); typeof(z)); </script> / i </head> • It is an unary operator. – Return either: Number, string, Boolean, , g, , object, function, undefined, null 27
  • 28. What is an Object? • An object is a thing, anything, just as things in the real world. – E.g. (cars, dogs, money, books, … ) • In the web browser, objects are the browser window itself, forms, buttons, text boxes, … • Methods are things that objects can do. – Cars can move, dogs can bark. – Window object can alert the user “alert()”. • All objects have properties properties. – Cars have wheels, dogs have fur. – Browser has a name and version number. 28
  • 29. Array • An Array contains a set of d i f data represented b d by a single variable name. • Arrays in JavaScript are represented by the Array Object, we need to “new Array()” to y j , y() construct this object. • The first element of the array is “Array[0]” Array[0] until the last one Array[i‐1]. • E myArray = new A E.g. A Array(5) (5) – We have myArray[0,1,2,3,4]. 29
  • 30. Array Example <script language=“JavaScript”> language= JavaScript” Car = new Array(3); Array(3 Car[0 Car[0] = “Ford”; Car[1 Car[1] = “Toyota”; y Car[2 Car[2] = “Honda”; document.write(Car[0 “<br>”); document.write(Car[0] + “<br>”); document.write(Car[1 “<br ”) document.write(Car[1] + “<b >”); d i (C [ [1 “ br>”); document.write(Car[2 “<br>”); document.write(Car[2] + “<br>”); </script> • You can also declare arrays with variable length. – arrayName = new Array(); – Length = 0, allows automatic extension of the length. 30 – Car[9] = “Ford”; Car[99] = “Honda”;
  • 31. Null & Undefined • An “ d f d” value is returned when you “undefined” l d h attempt to use a variable that has not been defined or you have declared but you forgot to provide with a value. • Null refers to “nothing” • You can declare and define a variable as “null” null if you want absolutely nothing in it, but you just don’t want it to be “undefined”. don t undefined 31
  • 32. Null & Undefined example <html> <head> <title> Null and Undefined example </title> <script language=“JavaScript”> var test1, test2 = null; test1 test2 alert(“No value assigned to the variable” + test1); test1 alert(“A null value was assigned” + test2); test2 </script> p </head> <body> … </body> </html> m 32
  • 33. JavaScript Special Characters l h Character Meaning b Backspace B k f Form feed t Horizontal tab n New line r Carriage return Backslash k l h ’ Single quote g q 33 ” Double quote
  • 34. Operators • Arithmetic operators • Logical operators • Comparison operators • String operators • Bit wise Bit‐wise operators • Assignment operators • Conditional operators 34
  • 35. Arithmetic operators left_operand “operator” right_operand • Operator Name Description Example + Addition Adds the operands 3+5 - Subtraction Subtracts the right operand 5-3 from the left operand * Multiplication Multiplies the operands 3*5 / Division Divides the left operand by the 30 / 5 right operand % Modulus Calculates the remainder 20 % 5 35
  • 36. Unary Arithmetic Operators • Binary operators take two operands. • Unary type operators take only one operand. y yp p y p • Which one add value first, and then assign value to the variable? Name Example Post Incrementing operator Counter++ Post Decrementing operator Counter-- Counter-- Pre Incrementing operator ++counter ++counter Pre Decrementing operator --counter --counter 36
  • 37. Logical operators • Used to perform Boolean operations on Boolean operands Operator Name Description Example && Logical and Evaluate to “true” when both true” 3>2 && operands are true 5<2 || Logical or Evaluate to “true when either 3>1 || 2>5 operand is true ! Logical not Evaluate to “true” when the true” 5 != 3 operand is false 37
  • 38. Comparison operators • Used to compare two numerical values Operator Name Description Example == Equal Perform type conversion before checking the “5” == 5 equality lit === Strictly equal No type conversion before testing “5” === 5 != Not equal “true” when both operands are not equal true” 4 != 2 !== Strictly not equal No type conversion before testing nonequality 5 !== “5” > Greater than “true” if left operand is greater than right operand true” 2>5 < Less than “true” if left operand is less than right operand true” 3<5 >= Greater than or “true” if left operand is greater than or equal to the true” 5 >= 2 equal q right operand g p <= Less than or “true” if left operand is less than or equal to the true” 5 <= 2 38 equal right operand
  • 39. Strict Equality Operators <script language=“JavaScript”> scr pt language JavaScr pt var currentWord=“75”; currentWord=“75”; var currentValue=75; currentValue=75; var outcome1=(currentWord == currentValue) outcome1=(currentWord t ( tW d currentValue); tV l ); var outcome2=(currentWord === currentValue); outcome2=(currentWord currentValue); alert(“outcome1 alert(“outcome1: “ + outcome1 + “ : outcome2: “ + outcome2); outcome1 outcome2 outcome2 </script> • Surprised that outcome1 is True! p • JavaScript tries very hard to resolve numeric and string differences differences. 39
  • 40. String operator • JavaScript only supports one string operator for joining two strings. Operator Name Description Return value + String Joins two strings “HelloWorld” HelloWorld” concatenation <script language=“JavaScript”> var myString = “” S i “”; myString = “Hello” + “World”; alert(myString); alert(myString); ( y g) g) </script> </script> 40
  • 41. Bit Manipulation Bi M i l i operators • Perform operations on the bit representation of a value, such as shift left or right value right. Operator Name Description & Bitwise AND Examines each bit position | Bitwise OR If either bit of the operands is 1, the result will be 1 ^ Bitwise Bit i XOR Set the S t th result bit only if either bit is 1, b t not b th lt bit, l ith i but t both << Bitwise left Shifts the bits of an expression to the left shift >> Bitwise signed Shifts the bits to the right, and maintains the sign right shift >>> Bitwise zero-fill Shifts the bits of an expression to right zero- right shift 41
  • 42. Assignment operators • Used to assign values to variables Operator Description Example = Assigns the value of the right operand to the left operand A=2 += Add the operands and assigns the result to the left A += 5 operand -= Subtracts the operands and assigns the result to the left A -= 5 operand *= Multiplies the operands and assigns the result to the left A *= 5 operand d /= Divides the left operands by the right operand and assigns A /= 5 the result to the left operand %= Assigns the remainder to the left operand A %= 2 42
  • 43. The most common problem <script language=“JavaScript”> if ( l h = b t ) { … } (alpha beta) if (alpha == beta) { … } </script> / i t • Don’t mix the comparison operator and Don t the assignment operator. • double equal sign (==) and the equal operator ( ) p (=) 43
  • 44. Order of Precedence Precedence Operator 1 Parentheses, function calls 2 , ~, -, ++, --, new, void, delete --, 3 *, / * /, % 4 +, - 5 <<, >>, >>> 6 <, <=, >, >= 7 ==, !=, ===, !== 8 & 9 ^ 10 | 11 && 12 || 13 ?: 14 =, +=, -=, *=, … 44 15 The comma (,) operator
  • 45. Precedence Example Value = (19 % 4) / 1 – 1 - !false (19 Value = 3 / 1 – 1 - !false Value = 3 / 1 – 1 - true Value = 3 – 1 - true Value V l =3–2 Value = 1 45
  • 46. Scope of a Variable • When you use a variable i a JavaScript h i bl in i program that uses functions. • A global scope variable is one that is declared outside a function and is accessible in any part yp of your program. • A local variable is declared inside a function and stops existing when the function ends. 46
  • 47. Example of variable data types variable, <html><head><title> Billing System of Web Shoppe </title></head><body> <h1 g <h1 align="center"> Billing System of Web Shoppe </h1> g y f pp </h1 <script language="JavaScript"> firstCustomer = new Array(); billDetails = new Array(firstCustomer); Array(firstCustomer); var custName, custDob, custAddress, custCity, custPhone; custName, custDob, custAddress, custCity, custPhone; var custAmount, custAmountPaid, custBalAmount; custAmount, custAmountPaid, custBalAmount; custName=prompt("Enter custName=prompt("Enter the first customer's name:", ""); custDob=prompt("Enter custDob=prompt("Enter the first customer's date of birth:", ""); custAddress=prompt("Enter custAddress=prompt("Enter the first customer's address:", ""); custPhone=prompt("Enter custPhone=prompt("Enter the first customer's phone number:", ""); custAmount=prompt("Enter custAmount=prompt("Enter the total bill amount of the first customer:", ""); custAmountPaid=prompt("Enter custAmountPaid=prompt("Enter the amount paid by the first customer:", ""); custBalAmount = custAmount - custAmountPaid; custAmountPaid; firstCustomer[ ]=custName; firstCustomer[0]=custName; firstCustomer[ ]=custDob; firstCustomer[1]=custDob; ] firstCustomer[ ]=custAddress; firstCustomer[2]=custAddress; firstCustomer[ ]=custPhone; firstCustomer[3]=custPhone; firstCustomer[ ]=custBalAmount; firstCustomer[4]=custBalAmount; document.write("<B>" document.write("<B>" + "You have entered the following details for first customer:" + "<BR>"); document.write( Name: " + billDetails[0][0] + "<BR>"); document.write("Name: document write( write("Name: billDetails[ ][0 <BR> ); document.write("Date document.write("Date of Birth: " + billDetails[0][1] + "<BR>"); billDetails[ ][1 document.write("Address: document.write("Address: " + billDetails[0][2] + "<BR>"); billDetails[ ][2 document.write("Phone: document.write("Phone: " + billDetails[0][3] + "<BR>"); billDetails[ ][3 (custBalAmount == 0) ? document.write("Amount Outstanding: " + custBalAmount):document.write("No amount due") document.write("Amount custBalAmount):document.write("No </script></body></html> / /b d /h l 47
  • 48. Output of the code 48
  • 49. Conditional Statement • “if” statement • “if … else” statement if else • “else if” statement • “if/if … else” statement • “switch” statement 49
  • 50. “if” statement if if (condition) { statements; } condition) • It is the main conditional statement in JavaScript. JavaScript • The keyword “if” always appears in lowercase. • The condition yields a logical true or false value. • The condition is true, statements are executed. 50
  • 51. “if” statement example if <script language=“JavaScript”> var chr = “”; … if (chr == ‘A’ || chr == ‘O’) { (chr document.write(“Vowel document.write(“Vowel variable”); } </script> “||” operator ‐ increase the speed of the script 51
  • 52. “if … else” statement if else if (condition) { statements; } condition) else { statements; } • You can include an “else” clause in an if statement when you want to execute some statements if the condition is false. 52
  • 53. Ternary Sh T Shortcut ( (concise) i ) <script language=“JavaScript”> If (3 > 2) { (3 alert(“True”); } else { alert(“False”); } (3 > 2) ? alert(“True”) : alert(“False”); l t(“T ”) l t(“F ls ”) </script> • Substitute for a simple “if/else” statement. 53
  • 54. “else if statement else if” if (condition) { statement; } condition) else if (condition) { statement; } condition) else { statement; } • Allows you to test for multiple expression for one true value and executes a particular bl k of code. ti l block f d 54
  • 55. “if/if else” statement example if/if…else <script language=“JavaScript”> var chr; chr; chr = prompt(“Please enter a character : “,””); if (chr >= ‘A’){ (chr ){ if (chr <= ‘Z’) (chr alert( Uppercase ); alert(“Uppercase”); else if (chr >= ‘a’){ (chr alert(“Lowercase”); alert( Lowercase ); } } 55 </script>
  • 56. “switch” statement switch switch (expression) { expression) case label1: label l b l1 l1 statements; break; default: d f lt statements; } • Allows you to merge several evaluation tests of the same variable into a single block f t t bl k of statements. t 56
  • 57. “switch” statement example switch <script language=“JavaScript”> var chr; chr; chr = prompt(“Pls enter a character in lowercase:”,””); prompt(“Pls switch(chr){ switch(chr){ case ‘a’ : alert(“Vowel a”); break; case ‘‘e’’ : alert(“Vowel e”); break; default : alert(“Not a vowel”); } </script> 57
  • 58. Looping Statement “for” Loops • “for/in” Loops for/in • “while” Loops • “do … while” Loops • “break” statement break • “continue” statement • 58
  • 59. “for” statement for for (initial_expression; test_exp; change_exp) initial_expression; test_exp; change_exp) { statements; } t t t • One of the most used and familiar loops is the for loop. • It iterates through a sequence of statements for a number of times controlled by a condition. • The change exp determines how much has change_exp been added or subtracted from the counter variable. 59
  • 60. “for” statement example for <script language=“JavaScript”> var counter; for (counter = 1; counter <= 10; counter++) 10; counter++) { document.write(counter*counter document.write(counter*counter + “ “); } </script> • Display the square of numbers • Output: 1 4 9 16 25 36 49 64 81 100 60
  • 61. “for/in” statement for/in for (counter_variable in object) { statements; } t t t • When the for/in statement is used, the counter and termination are determined by the length of the object. j • The statement begins with 0 as the initial value of the counter variable, terminates with all the properties of the objects have been exhausted. – E.g. array no more elements found 61
  • 62. “for/in” statement example for/in <script language=“JavaScript”> var b k (Wh t is the difference if “var book=“”;) book; (What i th diff “var b k “” ) var booklist = new Array(“Chinese”, “English”, “Jap”); for (var f (var counter i b kli t) { t in booklist booklist) t) book += booklist[counter] + “ “; } alert(book); </script> 62
  • 63. “while” statement while initial value declaration; while (condition) { hil condition) diti statements; increment/decrement statement; i t/d t t t t } • The while loop begins with a termination condition and keeps looping until the termination condition is met. • The counter variable is managed by the context of the statements inside the curly braces. 63
  • 64. “While” statement example While <html> <head> <title>While loop example</title> <script language=“JavaScript”> var counter = 100; t 100; var numberlist = “”; while (counter > 0) { numberlist += “Number “ + counter + “<br>”; “<br>”; counter -= 10; 10; } document.write(numberlist); document.write(numberlist); </script> <body> … </body> /s i t> b d > /b d > 64 </html>
  • 65. “do … while” statement do while do { statements; t t t counter increment/decrement; } while (t hil termination condition) i ti condition) diti • The do/while loop always executes statements in the loop in the first iteration of the loop loop. • The termination condition is placed at the bottom of the loop. 65
  • 66. Example of Flow Control 66
  • 67. Outline – Part B • JavaScript Functions and Events i i d – Events Handlers • Using Object in JavaScript – Object‐Oriented Programming Object Oriented – JavaScript Object Model – Using Built In objects (Predefined Object) Built‐In – Custom Object Types • E Error i J S i in JavaScript • Exception Handling in JavaScript p g p 67
  • 68. Functions • Affunction i a bl k of organized reusable i is block f i d bl code (a set of statements) for performing a single or related action. • Begins with keyword “function” and the g y function name and “( … )” • Inside the parentheses – We can pass parameters to the function – E f ti myfuc(arg1, arg2) { } E.g. function f ( 1 2) {…} – Built‐in and user‐defined functions 68
  • 69. Built‐In Built In Functions • F Functions provided b the l i id d by h language and you cannot change d h them to suit your needs. • Some of the built‐in functions in JavaScript are shown here: built in – eval ‐ eval(expr) • eval evaluates the expression or statements – isFinite • Determines if a number is finite – isNaN • Determines whether a value is “Not a Number” – parseInt • Converts string literals to integers no number integers, NaN. NaN – parseFloat • Finds a floating‐point value at the beginning of a string. 69
  • 70. User‐Defined User Defined Functions • For some functionality, you cannot achieve by only using the built‐in functions. y g • You can define a function as follows function <function_name> (parameters) function_name> { // code segments; 70 }
  • 71. Function Declarations • Declaration Syntax – Functions are declared using the function reserved word g – The return value is not declared, nor are the types of the arguments – Examples: function square(x) { return(x * x); } square(x) function factorial(n) { factorial(n) if (n <= 0) { return(1 return(1); } else { return(n * factorial(n - 1)); } } 71
  • 72. Events • Events are the actions that occur as a result of browser activities or user interactions with the web pages. – Such as the user performs an action (mouse click or enters data) – W can validate th d t entered b a user i a We lid t the data t d by in web form – Communicate with Java applets and browser plug‐ ins 72
  • 73. Event Categories • K b d and mouse events Keyboard d – Capturing a mouse event is simple • Load events d – The page first appears on the screen: “Loads”, leaves: “Unloads”, … Unloads • Form‐related events – onFocus() refers to placing the cursor into the text input in the form. • Others – Errors, window resizing. 73
  • 74. Events defined by JavaScript HTML elements HTML JavaScript Description tags defined events Link <a> click Mouse is clicked on a link dblClick Mouse is double-clicked on a link double- mouseDown Mouse button is pressed mouseUp Mouse button is released mouseOver O Mouse M is moved over a link i d li k Image <img> load Image is loaded into a browser abort Image loading is abandoned error An error occurs during the image loading Area <area> mouseOver The mouse is moved over an image map area mouseOut The mouse is moved from image map to outside dblClick The mouse is double-clicked on an image map double- Form <form> submit The user submits a form Reset The user refreshes a form … … … … 74
  • 75. Event Handlers • When an event occurs, a code segment i h d is executed in response to a specific event is called “ “event handler”. ” • Event handler names are quite similar to the q name of events they handle. • E g the event handler for the “click” event is E.g click “onClick”. • <HTMLtag eventhandler=“JavaScript Code”> 75
  • 76. Event Handlers Event Handlers Triggered when onChange The value of the text field, textarea, or a drop down list is modified onClick Cl k A l k an image or a form element is clicked once link, f l l k d onDblClick The element is double-clicked double- onMouseDown The user presses the mouse button onLoad A document or an image is loaded onSubmit A user submits a form onReset The form is reset onUnLoad The user closes a document or a frame onResize A form is resized by the user 76
  • 77. onClick event Handler <html> <head> <title>onClick Event Handler Example</title> <script language=“JavaScript”> p language= JavaScript” g g p function warnUser(){ return confirm(“INE2720 students?”); } confirm(“INE2720 </script> </head> /h d <body> <a href=“reference html”, onClick=“return warnUser();”>INE2720 href= reference.html onClick=“return warnUser();”>INE2720 onClick= = >INE2720 >INE Students access only</a> </body> </html> 77
  • 78. onLoad event Handler <html> <head> <title>onLoad and onUnload Event Handler Example</title> </head> <body onLoad=“alert(‘Welcome User’);” onLoad=“alert(‘Welcome User’);” onUnload=“alert(‘Thanks onUnload=“alert(‘Thanks for visiting the page’);”> page’);”> Load and UnLoad event test. </body> </html> 78
  • 79. User E U Events, Form E F Example l <html><head> <title>Simple JavaScript Button</title> <script language= JavaScript ><! language=“JavaScript"><!-- function dontClick() { alert("I told you not to click!"); } // --></script> </head> <body> <h1>Simple JavaScript Button</h1> <form> <input type=“button" value="Don't Click Me" onClick="dontClick()"> </form> </body></html> 79
  • 80. onMouseOver and onMouseOut Event Handlers <html> <head> h d> <title>onMouseOver and onMouseOut event handler</title> </head> /head <body> <a href=“link.html” onMouseOver = “status = ‘Now mouse is over the link’; “ onMouseOut = “status = ‘Mouse has moved out’;”> A Link Page </a> </body> /body </html> 80
  • 81. Understanding JavaScript Objects • One of the most important features of JavaScript, enables modular programs. • Objects are based on Classes, variables, functions, statements are contained in a structure called class. Class varA varB varC varD FunctionA (…) FunctionB (…) FunctionC ( ) (…) FunctionD ( ) (…) 81
  • 82. Class and Object • You can instantiate an object from a class by using the constructor function. • JavaScript is said to be an Object‐based programming language. • What is property? – A variable belongs to the object. • What is method? – It is a function belongs to the object object. – Function‐Valued Properties 82
  • 83. Creating Instances of Objects f b • You can use the “new” operator to create instances of objects of a particular class or object type. – Variable = new objectType(parameters) • This objectType() is called constructor. • E.g. Date is a predefined object type. – Assign the current date and time to objA g j • objA = new Date() – Assign another date and time to objB • objB = new Date(99,23,5) 23 May, 99 83
  • 84. Objects and Classes • Fields Can Be Added On‐the‐Fly i ld dd d h l – Adding a new property (field) is a simple matter of assigning a value to one – If the field doesn’t already exist when you try to assign to it, JavaScript will create it automatically. – For instance: var test = new Object(); test.field1 test field1 = "Value 1"; // Create field1 property Value 1 ; test.field2 = 7; // Create field2 property 84
  • 85. Objects and Classes – Literal Notation • You Can Use Literal Notation Y C U Lit l N t ti – You can create objects using a shorthand “literal” notation of the form { field1:val1, field2:val2, ... , fieldN:valN } – For example, the f ll l h following gives equivalent values to object1 and l l d object2 var object1 = new Object(); var object2 = new Object(); object1.x = 3; object1.y = 4; j y object1.z = 5; object2 = { x:3, y:4, z:5 }; 85
  • 86. Objects and Classes ‐ Constructor • A “Constructor” is Just a Function that Assigns to “this” • JavaScript does not have an exact equivalent to Java s class definition Java’s • The closest you get is when you define a function that assigns values to properties in the this reference • Calling this function using new binds this to a new Object • For example, following is a simple constructor for a Ship class function Ship(x, y, speed, direction) { this.x = x; this.y this y = y; this.speed = speed; this.direction = direction; } 86
  • 87. Constructor, Constructor Example var ship1 = new Ship(0, 0, 1, 90); 87
  • 88. Class Methods Example Methods, function degreesToRadiansversion of the Ship class that includes a move method degreesToRadians(degrees) { Consider a (degrees) • return(degrees * Math.PI / 180.0); 180. } function move() { var angle = degreesToRadians(this direction); degreesToRadians(this.direction this.direction); direction); this.x = this.x + this.speed * Math.cos(angle); this.y = this.y + this.speed * Math.sin(angle); } function Ship(x, y, speed, direction) { this.x = x; this.y = y; this.speed = speed; this.direction = direction; this.move = move; hi } 88
  • 89. Class Methods Result Methods, var ship1 = new Ship(0, 0, 1, 90); ship1.move(); ship1 move(); 89
  • 90. Objects and Classes ‐ Arrays • Arrays A • For the most part, you can use arrays in JavaScript a lot like Java arrays. • Here are a few examples: var squares = new Array(5); A (5) for(var i=0; i<squares.length; i++) { vals[i] = i * i; } // Or, in one fell swoop: var squares = new Array(0, 1, 4, 9, 16); var array1 = new Array("fee", "fie", "fo", "fum"); // Literal Array notation for creating an array. var array2 = [ "fee", "fie", "fo", "fum" ]; • Behind the scenes, however, JavaScript simply represents arrays as objects with numbered fields • You can access named fields using either object.field or object["field"], but numbered fields only via object[fieldNumber] 90
  • 91. Array, Array Example var arrayObj = new Object(); arrayObj[0] = "Index zero"; arrayObj[10] = "Index ten"; arrayObj.field1 arrayObj field1 = "Field One"; Field One ; arrayObj["field2"] = "Field Two"; 91
  • 92. Build‐In J S i Objects B ild I JavaScript Obj Object Description Array Creates new array objects Boolean Creates new Boolean objects j Date Retrieves and manipulates dates and times Error Returns run-time error information run- Function Creates new function objects Math Contains methods and properties for performing mathematical calculations l l ti Number Contains methods and properties for manipulating numbers. String Contains methods and properties for manipulating text strings 92
  • 93. JavaScript References http://developer.netscape.com/docs/manuals/communicator/jsref/contents.htm 93
  • 94. Error and Exception Handling in JavaScript • While executing your code, runtime hil i d i exceptions occur. • How can you write error‐free scripts? – The onerror event handler – The Error object • http://www irt org/xref/Error htm http://www.irt.org/xref/Error.htm – The throw statement – The try … catch … finally block • Error and Exception are the same. 94
  • 95. onerror Event Handler • E Errors may occur d t due to – syntax errors •S Syntax i the rules of grammar and spelling is h l f d lli – runtime errors • The script tries to perform something the system (browser) cannot do. • To capture error event, JavaScript provides the onerror event handler. • The onerror event handler is associated with the window object. 95
  • 96. How to use “onerror” event handler? onerror <html> <head> <title>onerror event handler example /title <title>onerror title example</title> <script language=“JavaScript”> Function errorHandler(){ errorHandler(){ alert( an alert(“an error has ocurred”); ocurred”); ); } window.onerror = errorHandler; errorHandler; </script> </head> <body> <script l i language=“JavaScript”> “J i ” document.write(“Hello document.write(“Hello there; </script> </body> 96 </html>
  • 97. Exception Handling in JavaScript • An exception is an error generated by the script. • Th code that h dl an exception i called an The d h handles i is ll d exception handler that will catch exceptions. Normal script flow of control p The exception is caught and handled by an exception handler If an error is occurred, An exception will be thrown. 97
  • 98. try … catch … finally try { // normal statements // might result in an error, throw exceptions } catch(errorVariable) catch(errorVariable) { // statements that execute in the exception event } finally { // After the execution in the catch or try block, // the statements in the finally block are executed. h i h fi ll bl k d 98 }
  • 99. Try … catch … finally example <script language=“JavaScript”> try{ document.write(“Try document.write(“Try block begins” + “<br>”); “<br>”); // create a syntax error eval (“10 + * 5”); (“10 }catch(errVar){ catch(errVar){ document.write( Exception caught document write(“Exception caught” + “<br>”); document.write( write(“Exception “<br> ); <br>”); <br> document.write(“Error document.write(“Error name: “ + errVar.name + “<br>”); “<br>”); document.write(“Error document.write(“Error message: “ + errVar.message + “<br>”); “<br>”); }finally{ f ll { document.write(“Finally document.write(“Finally block reached!”); } </script> 99
  • 100. Outline – Part C • Working with Browser Objects – Document Object Model (DOM) • Window, document, history, location Objects • Properties and Methods –F Form V lid ti S i t Validation Script • Creating Cookies in JavaScript – Constructing a standard cookie – Cookie Property – Interaction with the cookie – Using JavaScript to manipulate HTTP cookies 100
  • 101. Using Browser Objects • In the previous lectures, you were introduced to predefined objects in JavaScript – Math, String, Object, Boolean, Date, … • JavaScript also provides you with objects that can control and manipulate the displays of browsers. – More dynamic and interactive. y • When a browser loads a webpage, it creates a number of JavaScript objects. 101
  • 102. Document Object Model (DOM) history • DOM i an object‐oriented model that d is bj i d d l h describes h ib how all elements in an HTML page are arranged. • I is used to l It i d locate any object i your HTML page ( bj in (an unique address). • Th There are diff different DOM l l levels – The Level 0 DOM (DOM0) – The Level Th L l 1 DOM (DOM1) – The Level 2 DOM (DOM2) – The Level 3 DOM (DOM3) • Under development 102
  • 103. How the DOM works? <head><script> function toggle() { document.img.button1.src=“button_on.gif”; } document.img.button1 </script></head> reaction action <body> <a href=“test.html” onmouseover=“toggle()”> <img name=“button1” src=“button_off.gif”></a> href=“test.html” onmouseover=“toggle()”> <img name=“button1 src=“button_off.gif”></a> </body> Action Event JavaScript DOM Reaction src=“button_off.gif” onmouseover toggle() document.img.button1 Src=“button_on.gif” User moves mouse over object (١ Event senses that something happened to the object (٢ JavaScript tells the object what to do (Even handler) (٣ Locates object on the web page (۴ 103 Object’s image source is changed (۵
  • 104. Browser Hierarchy Model window document frame location history anchor image form link button checkbox radio select reset textarea text submit 104
  • 105. The “window” Object window • It is the highest‐level object in the JavaScript browser object hierarchy. • It is the default object and is created automatically when a page is loaded. • Since it is the default object, we may omit writing window e p c y do explicitly. – document.write(“a test message”); – window.document.write(“a test message”); • It also includes several properties and methods for us to manipulate the webpage. p p g 105
  • 106. Properties and methods of the “window” Object Property Description length An integer value representing the number of frames in the window name A string value containing the name of a window parent A string value containing the name of the parent window status A string value representing status bar text Method Description alert(text) Pop up a window with “text” as the message text” close() Closes the current window open(url) Open a new window populated by a URL. setTimeout(expression, time) Executes an expression after the elapse of 106 the interval time.
  • 107. Example of using the “window” Object window • Opening and closing windows • Window attributes of the “open()” method Attribute Description p toolbar Creates the standard toolbar location Creates the location entry field directories Creates standard directory buttons status Creates the status bar menubar Creates the menu bar at the top of a window scrollbars Creates scrollbars when the document exceeds the window size resizable Enables the user to resize the window width Specifies the width of the window 107 height Specifies the height of the window
  • 108. The “document” Object document It is one of the important objects in any window or • frame. The document object represents a web document or • a page in a browser window. When you access multiple sites simultaneously, there • would be multiple windows ope ed ou d u pe do s opened. Each window would have a corresponding window object, – and each window object would have its own document j object. 108
  • 109. Properties and methods of the “document” Object Property Description bgColor A string value representing the background color of a document alinkColor A string value representing the color for active links location A string value representing the current URL g p g title A string value representing the text specified by <title> tag Method Description clear() Clears the document window write(content) ite(content) Writes the text of content to a doc ment W ites te t document writeln() Writes the text and followed by a carriage return open() Open a document to receive data from a write() stream 109 close() Closes a write() stream
  • 110. The “history” Object history Each time you visit a web page and click on • h i ii b d li k the “Back” or “Forward” arrow buttons on your browser toolbar, you are accessing the history list. You can also add similar buttons / links that • allow users to move backward and forward via the information stored in the history object. 110
  • 111. Properties and methods of the “history” Object Property Description length An integer value representing the number of links in the history object current Contains the URL of the current page p g next Contains the URL of the next entry in the history list previous Contains the URL of the previous entry in the history list Method Description back() Sends the user to the previous page in the history list forward() Sends the user to the next page in the history list go(x) Sends back or forward by “x” number of pages in the history list 111
  • 112. The “form” Object form • The form object is accessed as a property of the document object. • Each form element in a form (text input field, radio buttons), is further defined by other objects. • The browser creates a unique “form” object for each form in a docu e o document. • You can access the form object “form1” – document form1 document.form1 112
  • 113. Form Element Based Objects Element‐Based • HTML forms can include eight types of input elements – Text fields, Textarea fields – Radio buttons – Check box buttons – Hidden fields – Password fields – Combo box select menu – List select menu – Each object has its own properties and methods. 113
  • 114. Form Validation Script <html><head> <html><head> <body> <title>Form Example</title> <h1 <h1>Form Example</h1> Example</h1 <script LANGUAGE="JavaScript"> LANGUAGE= JavaScript > <p>Enter the following information When you press the Display information. function validate() { button, the data you entered will be validated, then sent by email.</p> if (document.form1.yourname.value.length < 1) { (document.form1 alert("Please enter your full name."); <form name="form1" action="mailto:user@host.com" name="form1 return false; enctype="text/plain“ onSubmit="validate();"> yp p (); } if (document.form1.address.value.length < 3) { (document.form1 <p><b>Name:</b> <input type=“text" length="20" name="yourname"> length="20" name="yourname"> alert("Please enter your address."); </p> return f ls ; t n false; <p><b>Address:</b> <input type=“text" length="30" name="address"> p b Address /b input type text length="30" name="address"> length 30 name address } </p> if (document.form1.phone.value.length < 3) { (document.form1 <p><b>Phone: </b> <input type=“text" length="15" name="phone"> length="15" name="phone"> alert("Please enter your phone number."); </p> return f l t false; <p><input type=“submit" value="Submit"></p> type= submit value= Submit ></p> } return true; </form> } </body> </script> / </html> </head> 114
  • 115. Application: Using JavaScript to Validate CGI Forms 1. 1 Accessing F A i Forms – The document.forms property contains an array of Form entries contained in the document – As usual in JavaScript, named entries can be accessed via name instead of by number, plus named forms are automatically inserted as properties in the document object, so any of the following p p j , y g formats would be legal to access forms var fi tF m = d firstForm document.forms[0]; m t f m [0]; // Assumes <FORM NAME="orders" ...> var orderForm = document.forms["orders"]; F m um n .f m [ ]; // Assumes <FORM NAME="register" ...> var registrationForm = document.register; 115
  • 116. Application: Using JavaScript to Validate CGI Forms, cont. 2. Accessing Elements within Forms – The Form object contains an elements property that holds an array of Element objects – You can retrieve form elements by number, by name from the array, or via the property name: var firstElement = firstForm.elements[0]; // Assumes <INPUT ... NAME="quantity"> E " " var quantityField = orderForm.elements["quantity"]; // Assumes <INPUT ... NAME= submitSchedule > NAME="submitSchedule"> var submitButton = register.submitSchedule; 116
  • 117. Checking Form Values Individually, Example <html><head><title>On-Line Training</title> <script language=“JavaScript"> <!-- // Wh When the user changes and leaves t tfi ld check th h d l textfield, h k // that a valid choice was entered. If not, alert // user, clear field, and set focus back there. function checkLanguage() { // or document.forms["langForm"].elements["langField"] var field = document.langForm.langField; var lang = field.value; var prefix = lang.substring(0, 4).toUpperCase(); if (prefix != "JAVA") { alert("Sorry, '" + lang + "' is not valid.n" + "Please try again "); Please again. ); field.value = ""; // Erase old value field.focus(); // Give keyboard focus } } 117
  • 118. Checking Form Values Individually, Example, cont. // --> </script></head> <body><h1>On-Line Training</h1> y g <form action="cgi-bin/registerLanguage" name="langForm"> To see an introduction to any of our on-line training courses, please enter the name of an important Web programming language below. <p> <b>Language:</b> <input type=“text" name="langField" onFocus="describeLanguage()" onBlur="clearStatus()" onChange="checkLanguage()"> <p> <input type=“submit" value="Show It To Me"> </form> </body> </html> 118
  • 119. Checking Form Values Individually, Results 119
  • 120. Checking Values When Form is Submitted, Example <html><head><title>Camp Registration</title> <script language=“JavaScript"> <!-- ! function isInt(string) { var val = parseInt(string); return(val > 0); } function checkRegistration() { var ageField = document.registerForm.ageField; if (!isInt(ageField.value)) { alert("Age must be an integer."); return(false); } ... // Format looks OK. Submit form. return(true); } // --> 120 </script>
  • 121. Checking Values When Form is Submitted, Example, cont. <body><h1>Camp Registration</h1> <form action="cgi-bin/register“ name="registerForm" onSubmit="return(checkRegistration())"> ( g ()) Age: <input type=“text" name="ageField" onFocus="promptAge()" onBlur="clearStatus()"><br> Rank: <input type=“text" name="rankField" onFocus="promptRank()" onBlur="clearStatus()"><br> Serial Number: <input type=“text" name="serialField" onFocus="promptSerial()" onBlur="clearStatus()"><p> <input type=“submit" value="Submit Registration"> </form> </body> </html> /ht l 121
  • 122. Checking Values When Form is Submitted, Results 122
  • 123. Why we need Cookies? • The web servers process requests efficiently because they did not need to maintain any unique requirements for different clients. • Web browsers treat every visit to a web page as an entirely new session, even if users open a different web page on the same server. • The client information becomes more important for commercial purposes. p p 123
  • 124. Cookie Basics • When a user closes the browser, the information contained in a hidden form field will be lost. • A cookie is used to store information on the user’s computer even when the user switches off his/her computer. • It is a da a that is se from a web se e to a web s data a s sent o eb server o eb browser when the user visits a site on a server. – It is just a .txt file in a user’s computer. user s 124
  • 125. Features of Cookies • A cookie can b associated with one or more ki be i d ih documents on the web server. • More than one cookie can be associated with a document on the web server. • Every cookie has a NAME‐VALUE pair associated with it it. • Cookies have an expiration date associated with th ith them. 125
  • 126. Cookies Applications • Web page customization for each user • Form information storage • Shopping carts for order information • Store userID and password • Track how many times the user has visited • Maintain a past score for each player on a test or online games 126
  • 127. Application: Using JavaScript to Store and Examine Cookies 1. Using document.cookies – Set it (one cookie at a time) to store values ( ) document.cookie = "name1=val1"; document.cookie document cookie = "name2=val2; expires=" + someDate; name2 val2; expires document.cookie = "name3=val3; path=/; domain=test.com"; – Read it (all cookies in a single string) to access values 127
  • 128. Application: Using JavaScript to Store and Examine Cookies 2. 2 Parsing Cookies P i C ki function cookieVal(cookieName, cookieString) { var startLoc = cookieString indexOf(cookieName); cookieString.indexOf(cookieName); if (startLoc == -1) { return(""); // No such cookie } var sepLoc = cookieString.indexOf("=", startLoc); var endLoc = cookieString.indexOf(";", startLoc); if (endLoc == -1) { // Last one has no ";" endLoc = cookieString.length; } return(cookieString.substring(sepLoc+1, endLoc)); } 128
  • 129. Cookie, Cookie Example <html><head> <title>Widgets "R" Us</title> <script language=“JavaScript"> <!-- ! function storeCookies() { var expires = "; expires=Monday, 01-Dec-02 23:59:59 GMT"; var first = document widgetForm firstField value; document.widgetForm.firstField.value; var last = document.widgetForm.lastField.value; var account = document.widgetForm.accountField.value; document.cookie = "first=" + first + expires; document.cookie = "last=" + last + expires; document.cookie = "account=" + account + expires; } // Store cookies and give user confirmation. function registerAccount() { storeCookies(); () alert("Registration Successful."); } 129
  • 130. Cookie, Example, cont. Cookie Example cont f function cookieVal(cookieName, cookieString) { ( m , g) var startLoc = cookieString.indexOf(cookieName); if (startLoc == -1) { return(""); // No such cookie } var sepLoc = cookieString.indexOf("=", startLoc); var endLoc = cookieString.indexOf(";", startLoc); if (endLoc == -1) { // Last one has no ";" endLoc = cookieString length; cookieString.length; } return(cookieString.substring(sepLoc+1, endLoc)); } function presetValues() { var firstField = document.widgetForm.firstField; var lastField = document.widgetForm.lastField; var accountField = document widgetForm accountField; document.widgetForm.accountField; var cookies = document.cookie; firstField.value = cookieVal("first", cookies); lastField.value = cookieVal("last", cookies); accountField.value cookieVal( account accountField value = cookieVal("account", cookies); } // --></script></head> 130
  • 131. Cookie, Example, cont. Cookie Example cont <body onLoad="presetValues()"> onLoad= presetValues() > <h1>Widgets "R" Us</h1> <form action="servlet/cwp.Widgets" name="widgetForm" f ti " l t/ Wid t " " id tF " onSubmit="storeCookies()"> First Name: <input type=“text" name="firstField"><br> F N “ " "f F ld" b Last Name: <input type=“text" name="lastField"><br> Account Number: <input type=“text" name="accountField"><br> Widget Name: <input type=“text" name="widgetField"><br> <input type=“button" value="Register Account" onClick="registerAccount()"> <input type=“submit" value="Submit Order input type submit value Submit Order"> </form> </body> </html> 131
  • 132. Cookie, Example, Cookie Example Result 132
  • 133. Outline – Part D • I t d i DHTML Introducing – Styles and Layers – Dynamic Positioning – Moving objects in 3D – Internet Explorer Filters l il • Using DHTML and CSS Tools • Cool JavaScript Sites • JavaScript and DHTML Reference p • Summary 133
  • 134. Dynamic HTML • Everyone is a Web Designer. – Learning DHTML, CSS and JavaScript is your next step into the web design world. • “DHTML” is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated. • Web pages can be made to respond to users’ actions. • Problem: How to achieve “Dynamic”? Dynamic ? 134
  • 135. DHTML advantages / disadvantages • Supported b most b d by browsers • Small file sizes (faster than Flash) ( ) • No plug‐ins required • Easy to learn (learn HTML, JavaScript) HTML • Faster web experience (change the page content without l h load new pages) ) • Browser and OS incompatibilities p – The implementation of CSS, DOM varies from browser to browser 135
  • 136. What makes a web site dynamic? • I Interactivity – adapt and react to the visitor’s actions i i d d h ii ’ i as quick as possible. • S h i i – b i together relevant i f Synchronicity bring h l information i from a variety of sources. • Fl ibili – give the visitor diff Flexibility i h i i different ways to fi d find information in the site. • Ad Adaptability – adjusts to cater to i di id l visitor’s bili dj individual i i ’ needs. • A i i – uses motion and sound to d Activity i d d draw user’s ’ attention to changes on the site. 136
  • 137. The Role of each component in DHTML • With CSS, we can change the style of any ih h h l f HTML elements. • With DOM, we can have a map on every elements in the HTML page. p g • With JavaScript, we can access and have operations on the elements in the DOM tree tree. • With event handler, we can execute the predefined scripts at any ti d fi d i t t time. 137
  • 138. Cross‐Browser Cross Browser DHTML Netscape 4.x Cross-Browser Cross- Internet Explorer DHTML 4.x JavaScript CSS1 CSS2 CSS1, CSS2, Visual Filters Style Sheets CSS- CSS-Positioning allow you to apply (JSS) JavaScript p visual effects to Netscape DOM text or graphics Layers y Data Binding g (positioning, visibility) y) 138
  • 139. Open a new browser window • Pop‐up windows are useful for navigation pp controls, advertisements, supplementaryy contents. • You can open a window close the window or window, window, toggle the window. 139
  • 140. Dynamic Technique: Change CSS Styles • You can change or add to any CSS property defined for d fi d f any object on the screen. bj h onMouseOver() 140
  • 141. Change Background Color <html><head> <script language="JavaScript"> function bgChange(bg) { document.body.style.background=bg; } </script></head> <body><b>Mouse over these table cells, and the background color will change</b> <table width="300" height="100"> <tr> <td onmouseover="bgChange('red')" onmouseout="bgChange('transparent')" bgcolor="red"> </td> <td onmouseover="bgChange('blue')" onmouseout="bgChange('transparent')" bgcolor="blue"> </td> <td onmouseover="bgChange('green')" onmouseout="bgChange('transparent')” bgcolor="green"> </td> </tr> </table> </body></html> 141
  • 142. CSS Properties Reference: http://www.library.utoronto.ca/HTMLcourses/DHTML/properties1.html • 142
  • 143. Dynamic Positioning • It means the HTML elements can be positioned by using JavaScript JavaScript. • The element is moved by manipulating any of the “top”, “left”, “right” and top left right “bottom” CSS properties. • The more table you use the slower your use, page displays. • Positioning elements with CSS is more accurate than tables and the results are displayed much faster faster. 143
  • 144. Moving Objects from Point to Point • Using CSS, you can change the position of an object on the screen. bj h 144
  • 145. Moving Objects in 3 D 3‐D • By specifying the z‐index, we can put the objects i 3 D manner. bj t in 3‐D 145
  • 146. Moving the browser window • You can set an initial position of multiple windows. 146
  • 147. IE DHTML Visual Controls • The blurOn() Filter causes the image to blur bl on th screen. the 147
  • 148. IE Transition Filters • Produce transitions between web pages. Transition Reference # Box In 0 Box Out 1 Circle out 3 Wipe up 4 Wipe down 5 Wipe right Wi i ht 6 Wipe left 7 Random Dissolve 12 Random 23 148
  • 149. Adding last modified Date <html> <head> <title>Enter the title of your HTML document here</title> </head> <body> <script language=“JavaScript”> document.write( Page document write(“Page last modified: “ + document lastModified) document.lastModified) </script> </body> </html> 149
  • 150. Creating a Sliding Menu • Allow visitors to pull out menus or put them away. 150
  • 151. Follow the Mouse Pointer • The mouse pointer is part of the user interface that gives designer controls. g g 151
  • 152. Application: Using JavaScript to Make Pages Dynamic • Modifying Images Dynamically – The document.images property contains an g p p y array of Image objects corresponding to each IMG element in the current document – To display a new image, simply set the SRC property of an existing image to a string representing a different image file 152
  • 153. Modifying Images Example Images, • Th f ll i f The following function changes the fi i i h h first image i a d in document function changeImage() { document.images[0].src = "images/new-image.gif"; } • Referring to images by name is easier: <img src="cool-image.jpg" name="cool" im " l im jp " n m " l" width=75 height=25> function improveImage() { document.images["cool"].src = "way-cool.jpg"; } 153
  • 154. Modifying Images: A Clickable Image Button, Example <script language=“JavaScript"> <!-- imageFiles = new Array("images/Button1-Up gif", Array( images/Button1-Up.gif "images/Button1-Down.gif", "images/Button2-Up.gif", "images/Button2-Down gif"); images/Button2-Down.gif ); imageObjects = new Array(imageFiles.length); for(var i=0; i<imageFiles.length; i++) { imageObjects[i] = new Image(150 25); Image(150, imageObjects[i].src = imageFiles[i]; } function setImage(name, image) { document.images[name].src = image; } 154
  • 155. Modifying Images: A Clickable Image Button, Example function clickButton(name grayImage) { clickButton(name, var origImage = document.images[name].src; setImage(name, grayImage); var resetString = "setImage('" + name + "' '" + origImage + "')" " tI ('" "', i I "')"; setTimeout(resetString, 100); } // --></script> p </head>... <a href="location1.html" onMouseOver="clickButton('Button1', 'images/Button1-Down.gif')"> <img src="images/Button1-Up.gif" name="Button1" img src images/Button1 Up.gif name Button1 width=150 height=25></A> <a href="location2.html" onMouseOver="clickButton('Button2', 'images/Button2-Down.gif')"> <img src="images/Button2 Up gif" name= Button2 src= images/Button2-Up.gif name="Button2" width=150 height=25></A> ... 155
  • 156. Highlighting Images Under the Mouse, Example <html> ht l> <head> <title>High Peaks Navigation Bar</title> <script language=“JavaScript"> <!— // Given "Foo", returns "images/Foo.gif". Foo , images/Foo.gif . function regularImageFile(imageName) { return("images/" + imageName + ".gif"); } // Given "Bar", returns "images/Bar-Negative.gif". function negativeImageFile(imageName) { return("images/" + imageName + "-Negative.gif"); } 156
  • 157. Highlighting Images Under the Mouse, Example, cont. // Cache image at specified index. E.g., given index 0, // take imageNames[0] to get "Home". Then preload // images/Home.gif and images/Home-Negative.gif. function cacheImages(index) { regularImageObjects[index] = new Image(150, 25); regularImageObjects[index].src = regularImageFile(imageNames[index]); negativeImageObjects[index] = new Image(150, 25); negativeImageObjects[index].src = negativeImageFile(imageNames[index]); } imageNames = new Array("Home", "Tibet", "Nepal", "Austria", "Switzerland"); regularImageObjects = new Array(imageNames.length); negativeImageObjects = new Array(imageNames.length); // Put images in cache for fast highlighting. for(var i=0; i<imageNames.length; i++) { cacheImages(i); } 157
  • 158. Highlighting Images Under the Mouse, Example, cont. ... function highlight(imageName) { document.images[imageName].src = negativeImageFile(imageName); } function unHighlight(imageName) { document.images[imageName].src = regularImageFile(imageName); } // --> </script></head> <body> <table> <tr><td><a href="Tibet.html" target="Main" onMouseOver="highlight('Tibet')" onMouseOut="unHighlight('Tibet')"> <img src="images/Tibet.gif" name="Tibet“ width=150 height=25 border=0> </a> ... 158