Chapter 4
Java Script
            AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
                                                     lecture slides
     Introduction
 JavaScript   is the world's most popular programming
 language.
 JavaScript   is the programming language of the Web.
 JavaScript   is easy to learn.
A   scripting language is a lightweight programming
 language.
 JavaScript   code can be inserted into any HTML page, and
 it can be executed by all types of web browsers.
                                    AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
 2                                                                           lecture slides
                                                                                             …
 Why         JavaScript?
    JavaScript is one of the 3 languages all web developers must learn:
     1.    HTML to define the content of web pages
     2.    CSS to specify the layout of web pages
     3.    JavaScript to program the behavior of web pages
 You       can also use JavaScript to:
         Delete HTML elements
         Create new HTML elements
         Copy HTML elements
         And more ...
                                              AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
 3                                                                                     lecture slides
     Where to use?
 You  can write java script code either in heading part
  or body part.
 Before writing java script code you have to open
  <script> tag and close it at the end.
 You can place any number of scripts in an HTML
  document.
 And those can be both in <head> and <body>.
 But it is recommended to keep all your java script
  code (in a single page) together.
 Java script code can be found alone as external file
  saved with extension file .js.
                                 AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
 4                                                                        lecture slides
                                                                                                  …
 If your code is found externally then you have to call
  (link) it with the current page like:
       <script src="myScript.js"></script>
 You  are not expected to use <script> on external java
  script code.
        Java script is case sensitive (lower-case and upper-case letters have different
         meaning)
        Java script code can be used either in head or body part.
        Use semicolon at the end of single line code.
                                                   AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
 5                                                                                          lecture slides
     Comment
 JavaScript     comments can be used to explain JavaScript
 code.
    just like other language's comment, text under comment will not be
     executed.
 Itmakes your code more readable and prevent
  execution, when testing alternative code.
 Single-line and multi-line comment are used.
 Single line comments start with //.
    Any text starting with // up to the end of the line will be ignored by
     JavaScript (will not be executed).
 Multi-line     comments start with /* and end with */.
    Any text between /* and */ will be ignored by JavaScript.
                                               AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
 6                                                                                      lecture slides
    Example
              AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
7                                                      lecture slides
     JavaScript Output
 Java   script can display output in different ways:
    Writing into an HTML element, using innerHTML.
    Writing into the HTML output using document.write().
    Writing into an alert box, using window.alert().
 Using    innerHTML
  To   access an HTML element, JavaScript can use the
     document.getElementById(id) method.
  The   id attribute defines the HTML element.
  The   innerHTML property defines the HTML content
                                              AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
 8                                                                                     lecture slides
    Example
• <h1> has no element and it has id with the name "try".
• In the java script code, document.getElementById() is used to access any HTML
  element with its id.
                                              AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
9                                                                                      lecture slides
                                                                                             …
     • In this case, x has value "this is heading text" because we assigned
       the content of id called "try" to a variable x.
                                              AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
10                                                                                     lecture slides
                                                                                    …
 Using     window.alert()
 "alert"   is used to display message or text on a message
 box.
                                     AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
11                                                                            lecture slides
                                                                                          …
 using    document.write().
    "document.write()" is used to display text on your browser.
    Do not use this function except testing java script.
                                           AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
12                                                                                  lecture slides
    Function and event
   A JavaScript code in a function will execute only when some
    event calls it.
   Function is defined with the "function" keyword, followed by a
    name, then followed by parentheses ().
         Example: function try1()
   Function names can contain letters, digits, underscores, and dollar
    signs.
   The parentheses may include parameter names separated by
    commas: (parameter1, parameter2, ...)
                                          AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
13                                                                                 lecture slides
                                                                                     …
 The code to be executed, by the function, is placed inside curly
  brackets: { }
 Most often, JavaScript code is written to be executed when an
  event occurs, like when the user clicks a button.
 If we put JavaScript code inside a function, we can call that
  function when an event occurs.
 The following events can be used to call the function:
                                      AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
14                                                                             lecture slides
  Example
• On the code above, a button called "click" will display on the browser.
• Then when you click on the button, "Heading text" will display above the
  button with <h1> property.
• This happens because, when the user clicks on the button, the function
  "try1" is called and code under try1 will execute.
                                           AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
15                                                                                  lecture slides
    JavaScript Variables
 JavaScript variables are "containers" for storing data values.
 They can be used to hold values (x=5) or expressions (z=x+y).
 In java script, variables declared using the key word "var".
 Variable can have short names (like x, y and z) or more
  descriptive names (age, ID, FullName).
                                    AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
16                                                                           lecture slides
                                                                                 …
   While using variables in java script, we have to consider the
    following:
       Variable names must begin with a letter or $ or _
       Variable names are case sensitive (y and Y are different variables)
       Variable names can contain letters, digits, underscores, and dollar signs.
       Reserved words (like JavaScript keywords) cannot be used as names
   It is possible to declare and assign value to a variable at different line. Or
    you can do both at a time.
17
                                                                                         …
   You can declare many variables in one statement.
   Just start the statement with var and separate the variables by
    comma:
   Variable declared without a value will have the value
    undefined.
   If you re-declare a JavaScript variable, it will not lose its value.
                                          AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
18                                                                                 lecture slides
 JavaScript Operator
 Arithmetic   operators
                           Example
                           AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
19                                                                  lecture slides
                                                                          …
 Assignment   operators
 Example:
                           AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
20                                                                  lecture slides
                                                                          …
 Comparison   operators
                                     Example:
                           AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
21                                                                  lecture slides
                                                                                   …
 In   java script, the type of data that you are using is
 determined after value is assigned for the variable.
 Since   there are no different data types before value is
 assigned, the type of data is unknown until it is
 assigned.
 So   there are two things "type" and "value" for every
 variable result.
                                    AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
22                                                                           lecture slides
 String operator
     Operator   Meaning
     +          Concatenation
     +=         Concatenate and assign to left variable
                                 AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
23                                                                        lecture slides
                                                                                   …
 In   java script, if number and string are together, then
 they all will treat as a string.
 And    java script evaluates operation from left to right.
  <script>
        document.write(4 + 5 + "love"); //9love
        document.write("love" + 4 + 5); //love45
  </script>
                                    AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
24                                                                           lecture slides
 String methods
 Methods       Use                                         How?
 length        Returns string length                       var x=txt.length;
 indexOf       Returns the position of word                var y=txt.indexOf("home");
 search        Same with indexOf                           var y=txt.search("home");
 replace       Used to replace word with other             var y=txt.replace("home","house")
 toUpperCase   Changes lower case to upper                 var z=txt.toUpperCase( );
                                                 AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
25                                                                                        lecture slides
 Change HTML Styles (CSS)
 Youcan change HTML elements using java script
 code.
                             AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
26                                                                    lecture slides
 Conditional Statements
 Conditional   statements are used to perform different
 actions based on different conditions.
 Very   often when you write code, you want to
 perform different actions for different decisions.
 You   can use conditional statements in your code to
 do this.
                                 AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
27                                                                        lecture slides
                                                                                           …
 If   Statement
    Use the if statement to execute some code only if a specified condition
     is true.
           if (condition)
                {
                code to be executed if
           condition is true
                }
 Note: if is written in lowercase letters. Using uppercase letters
 (IF) will generate a JavaScript error!
                                            AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
28                                                                                   lecture slides
                                                                                            …
 If...else    Statement
    Use the if....else statement to execute some code if a condition is true
     and another code if the condition is not true.
      if (condition)
        {
      //code to be executed if condition is true
        }
      else
        {
      //code to be executed if condition is not true
        }
                                             AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
29                                                                                    lecture slides
                                                                                                …
 If...else     if...else Statement
    Use the if....else if...else statement to select one of several blocks of code
     to be executed.
        if (condition1)
          {
          code to be executed if condition1 is true
          }
        else if (condition2)
          {
          code to be executed if condition2 is true
          }
        else
          {
          code to be executed if neither condition1 nor
        condition2 is true
          }
                                                 AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
30                                                                                        lecture slides
                                                                                        …
 Example:
             <body>
                <button onClick='try1()'>click</button>
                <script>
                       function try1()
                       {
                       var x=prompt("enter your age");
                       if(x>20)
                              alert("you are legal");
                       else if(x>18)
                              alert("you have to wait");
                       else
                              alert("you are kid");
                       }
                </script>
             </body>
                                         AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
31                                                                                lecture slides
                                                                                   …
Note:
  Please   do not forget that java script is case sensitive
     and do not use upper case for if, else if and else.
  And    do not put semicolon (;) at the end of
     conditional statement (if, else if and else).
                                    AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
32                                                                           lecture slides
  JavaScript Loops
 In programming loop is used to do activities
  repeatedly.
 It will help us to iterate things as long as we want
  them.
 The    For Loop
    syntax:
       for (initiation; condition; increment/decrement)
         {
         the code block to be executed
         }
                                 AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
33                                                                        lecture slides
                                                                                …
 Semicolon    (;) is used to separate the three statements
  in for loop.
 Initiation is used to tell the loop where to start from.
 Condition is checked always before loop's code is
  executed.
 If condition is false, code won't be executed.
 Example:
              <script>
                 var i;
                 for(i=0;i<5;i++)
                 document.write(i);
              </script>          AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
34                                                                        lecture slides
                                                                                   …
 While    Loop
 The    while loop loops through a block of code as
     long as a specified condition is true.
 When      using while loop, initial value has to be set
     before the while loop.
 increment/decrement         must be there within the
     block code.
                                    AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
35                                                                           lecture slides
                                                                                  …
 Syntax:                           Example:
     while (condition)                   <script>
       {                                        var i=0;
       code block to be executed                while(i<5)
       }                                        {
                                                document.write(i);
                                                i++;
                                                }
                                         </script>
                                   AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
36                                                                          lecture slides
                                                                                               …
 Do/While           Loop
  The    do/while loop is a variant of the while loop.
  This    loop will execute the code block once, before checking the
     condition.
  If   the condition is true, and then it will repeat the loop as long as the
     condition is true.
                                do
                                  {
                                  code block to be executed
                                  }
                                while (condition);
                                                AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
37                                                                                       lecture slides
                                                                                        …
 Break     Statement
  The   break statement can be used to jump out of a loop.
  The   break statement breaks the loop and continues executing
     the code after the loop (if any).
 Continue          Statement
  The   continue statement breaks one iteration (in the loop), if a
     specified condition occurs, and continues with the next iteration
     in the loop.
                                         AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
38                                                                                lecture slides
                                                    …
     OUTPUT
     AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
39                                            lecture slides
                                                    …
     OUTPUT
     AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
40                                            lecture slides
  Form
 It   is possible to access values of form using java script
    it helps us to validate whether the user enters correct value
     or not.
 This   will help your site to be fast because validating
 value on the client rather than doing it on the server
 side.
                                       AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
41                                                                              lecture slides
 Lab 1: accessing form value
                 AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
42                                                        lecture slides
                                                                                                  …
 Description
    The form has a name "info" all inputs have name and the submit button, will
     call a function called "try1()" when it is clicked.
    When the function called, it goes to java script code and execute the block
     code under the function "try1()".
    "document.info.name.value" accesses the value of input box with the name
     "name".
    "info" is the name of the form and "name" is the name of the first input box
     "value" represents the content that the user enters on that text box.
    "if(x=="“)" checks if the user doesn't enter any value, then message box will
     display.
                                                   AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
43                                                                                          lecture slides
 Lab 2: Java script and HTML
                 AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
44                                                        lecture slides
 Lab 3: Confirm box
                AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
45                                                       lecture slides
                                                                                              …
 Description
    "confirm" is used to take input from the user as yes (true) or cancel
     (false).
    The code takes user confirmation and if the user says ok it will close the
     current window opened.
    Using "confirm" box, if the user press on yes, then it returns "true" else it
     returns "false".
    when the user press on "close" button, confirm box appears and asks if
     the user is sure.
    if the user click on "yes", which is "true" for the code, the window will
     close by the code "window.close();".
    If the user press on "cancel" which is "false" for the code, "window is not
     closing" message will appear by alert box.
    When this message appears, it displays in two lines because "\n" is used in
     between.
                                               AU/Computer Sc. Dept/Internet Programming( CoSc 3081)
46                                                                                      lecture slides
End of Chapter-4
               Thank You..!!!