GTU MCA PPT WTAD Unit-1 By Keval by nagaria.keval

VIEWS: 118 PAGES: 135

More Info
									Web Technology & Application
   Development (WTAD)

      Developed By:- Keval Nagaria

             Keval Nagaria           1

 Keval Nagaria   2
 Introduction to HTML – only basic structure and tags (up
 to table tag) of HTML
 Overview of Java Script
 Date and Time,
 Operations and Expressions
 Screen Output and Keyboard Input
 Control Statement
 Object Creation and Modification

                        Keval Nagaria                       3

Keval Nagaria   4
Markup Languages

Language   Year Introduced Description
SGML       1986             International standard for specifying
                            a document markup language
HTML       1992             An early recommendation
HTML+      1993             A superset of HTML
HTML 2.0   1995             An HTML version created by IETF
HTML 3.2   1996             W3C formal recommendation for
XML        1998             Universal format for structured
                            documents and data on the Web
XHTML      2000             Document markup language for the

                       Keval Nagaria                                5
Introduction To HTML
 What is HTML ?
   The language used to develop web pages is
    called Hyper Text Markup Language(HTML).
   HTML is the language interpreted by a
   Web pages are also called HTML documents.

   HTML is a set of special codes that can be
    embedded in text to add formatting and linking
   HTML is specified as TAGS in an HTML
    document(i.e The web Page)
                     Keval Nagaria                   6
  HTML is very easy to use. Web documents are
   typically written in HTML using any test editor
   such as Windows Notepad and are usually
   named with the suffix(extension) .html or .htm
  HTML documents are standard ASCII files
   with formatting codes that contain information
   about layout (text styles , document titles,
   paragraphs, lists) and links.
  After entering the HTML code in a file you can
   view it using any browser.
  NOTE:- Same web page might be interpreted
   differently by different browsers.
                    Keval Nagaria                    7
   Internet Explorer
   Netscape Navigator

   Firefox

     Text Editors
          Notepad(Windows), vi(Linux/Unix), Macintosh.
     Word Processors
          Microsoft Word, Word Perfect, Word Pro, AmiPro.
     HTML Editors
          Hotdog Pro, Web Weaver.
     Visual Editors
          Microsoft FrontPage, Netscape Composer, Adobe Page Mill, Dream
                                      Keval Nagaria                         8
Structure of an HTML
 Element Tag
 Special Character
 A complete HTML 4.0 Document
 Validating your HTML Tag

               Keval Nagaria    9
HTML Element / Tag
             <p align=“right”></p>

   Element    Attribute Name            Attribute Value

 You have to understand the important terms
 related to HTML.
 Not case-sensitive.

                        Keval Nagaria                     10
Main HTML Elements
  TITLE element required
  Optional Element
      BASE
      META

      BGSOUND

      SCRIPT


      STYLE

      LINK        Keval Nagaria   11
 BODY Element
  <BODY BGCOLOR=“black”>
  HTML Attributes and Attributes Value
      BGCOLOR

      TEXT


      OnLoad,OnUnload,OnFocus,OnBlur

 Element Inside BODY Element
    <BODY>
     Remaining HTML Element
     </BODY>        Keval Nagaria         12
Block-Level Elements
   H1….H6

 Basic Text Sections
   P

   PRE




                  Keval Nagaria   13
  OL
  LI

  UL
  LI

  DL

  DT

  DD

 Frames And Forms

               Keval Nagaria   14
  HR
  DIV


  MULTICOL(Netscape Only)

                Keval Nagaria   15
 Heading Types
     <H1 ...> ... </H1>
     <H2 ...> ... </H2>
     <H3 ...> ... </H3>
     <H4 ...> ... </H4>
     <H5 ...> ... </H5>
     <H6 ...> ... </H6>
 Attributes: ALIGN
     Values: LEFT (default), RIGHT, CENTER
 Nesting tags
     Headings and other block-level elements can contain
      text-level elements, but not vice versa

                           Keval Nagaria                    16
 Heading Example
  <TITLE>Document Headings</TITLE>
Samples of the six heading types:
<H1>Level-1 (H1)</H1>
<H2 ALIGN="CENTER">Level-2 (H2)</H2>
<H3><U>Level-3 (H3)</U></H3>
<H4 ALIGN="RIGHT">Level-4 (H4)</H4>
<H5>Level-5 (H5)</H5>
<H6>Level-6 (H6)</H6>

                           Keval Nagaria   17
P – The Basic Paragraph
 Attributes: ALIGN
     LEFT (default), RIGHT, CENTER. Same as headings.
     Whitespace ignored (use <BR> for line break)
          Consecutive <P>‟s do not yield multiple blank lines
     End Tag is Optional:

  <BODY>                         <BODY>
  <P>                            Paragraph 1
  Paragraph 1                    <P>
  </P>                           Paragraph 2
  <P>                            <P>
  Paragraph 2                    Paragraph 3
  </P>                           </BODY>
  <P>                            Equivalent with Implied Tags
  Paragraph 3
  Fully-Specified                 Keval Nagaria                  18
Preformatted Paragraphs
 The PRE Element
     <PRE> ... </PRE>
 Attributes: WIDTH
     Expected width in characters. Not widely supported.
 Problem: Special Characters
  if (a<b) {
  } else {

                          Keval Nagaria                     19
 Desired Character        HTML Required
<                        &lt;
>                        &gt;
&                        &amp;
"                        &quot;
Non-breaking space       &nbsp;

                Keval Nagaria             20
HTML Character Entities
 The “<“ character has special meaning in
 HTML documents
   We cannot use it directly in the text.
   We have to use a character entity.

   We must use “&lt;” or “&#60;”

   Note, they are case sensitive.

   The most common one is the non-breaking
    space – “&nbsp;”

                    Keval Nagaria             21
The most common entities

Display   Description           Name
          Non-breaking          &nbsp;
<         Less than             &lt;
>         Greater than          &gt;
&         Ampersand             &amp;
“         Quotation mark        &quot;
„         Apostrophe            &#39;

                Keval Nagaria            22
HTML Lists
 Unordred Lists
 Ordered Lists
 Definition Lists

                    Keval Nagaria   23
OL: Ordered (Numbered) Lists
 OL Element
     <OL>
     Attributes: TYPE, START, COMPACT
 List entries: LI
     <LI ...> ... </LI> (End Tag Optional)
     Attributes: (When inside OL) VALUE, TYPE

                           Keval Nagaria         24
UL: Unordered (Bulleted) Lists
 UL Element
     <UL>
 Attributes: TYPE, COMPACT
 List entries: LI (TYPE)

                           Keval Nagaria   25
Text-Level Elements
 Physical Character Styles
     FONT
          SIZE
          COLOR
          FACE
     SIZE
 Logical Character Styles

                           Keval Nagaria                    26
 Hypertext Links
    A
         HREF, NAME, TARGET, ...
    IMG
         SRC (required), ALT, ALIGN, WIDTH, HEIGHT, HSPACE,
 Misc. Text-Level Elements
    BR (Explicit line break)
    AREA (Client-side image maps)
    APPLET (Java)
    ...

                          Keval Nagaria                        27
OL Example
 <OL TYPE="I">
   <LI>Basic Text Sections
       <OL TYPE="A">
             <OL TYPE="1">
                <LI>The OL tag
                    <OL TYPE="a">
                <LI>The LI tag
             <OL TYPE="1">
                <LI>The UL tag
                <LI>The LI tag
             <OL TYPE="1">
                <LI>The DL tag
                <LI>The DT tag
                <LI>The DD tag

                                    Keval Nagaria   28
UL Example
     <UL TYPE="DISC">
       <LI>The UL tag
           <UL TYPE="CIRCLE">
               <UL TYPE="SQUARE">
       <LI>The LI tag
           <UL TYPE="CIRCLE">
               <UL TYPE="SQUARE">

                    Keval Nagaria   29
Physical Character Styles Example
<H1>Physical Character Styles</H1>
<TT>Teletype (Monospaced)</TT><BR>
Subscripts: f<SUB>0</SUB> + f<SUB>1</SUB><BR>
Superscripts: x<SUP>2</SUP> + y<SUP>2</SUP><BR>
<STRIKE>Strike Through</STRIKE><BR>
<B><I>Bold Italic</I></B><BR>
<BIG><TT>Big Monospaced</TT></BIG><BR>
<SMALL><I>Small Italic</I></SMALL><BR>

                             Keval Nagaria        30
Logical Character Style‟s Example
<H1>Logical Character Styles</H1>
<STRONG>Strongly Emphasized</STRONG><BR>
<SAMP>Sample Output</SAMP><BR>
<KBD>Keyboard Text</KBD><BR>
<EM><CODE>Emphasized Code</CODE></EM><BR>
<ACRONYM TITLE="Java Development Kit">JDK

                         Keval Nagaria                     31
Text Formatting

<b>               Bold text
<big>             Big text
<em>              Emphasized text
<i>               Italic text
<small>           Small text
<strong>          Strong text
<sub>             Subscripted text
<sup>             Superscripted text

             Keval Nagaria             32
HTML Links
 <a> to create a link to another document.
 The target attribute
  <a href=“…”, target=“_blank”>xxx</a>
  Open the document in a new browser window.

 The name attribute
  <a name=“abc”>
  <a href=“#abc”>Useful text</a>

                   Keval Nagaria                33
Hypertext Links
 Links can contain images and other text-level elements
 (i.e., <A HREF…> ... </A>)
 Link to Absolute URL
     Use a complete URL beginning with http://
       Java is discussed in
       <A HREF="http://host/path/chapter2.html">
       Chapter 2</A>.

 Link to Relative URL
     Use a filename or relative path to filename
        Interpreted wrt location of current file
       Java is discussed in
       <A HREF="chapter2.html">Chapter 2</A>.

                               Keval Nagaria              34
 Link to Section
    Use a section name (see below) preceded by #
      Images are discussed in
      <A HREF="#Section2">Section 2</A>.

 Link to Section in URL
    Use absolute or relative URL, then #, then section name
      Images are discussed in
      <A HREF="chapter1.html#Section2">
      Sec. 2 of Chap. 1</A>.
 Naming a Section
    Use <A NAME="..."> and do not include the pound sign
      <H2><A NAME="Section2">Images</A></H2>

                             Keval Nagaria                     35
      Link Example
                                                                                Text between strong tags will
   <head>                                                                               appear bold.
     <title>Internet and WWW How to Program - Links</title>

                                                                          Linking is accomplished in XHTML
                                                                              with the anchor (a) element.
     <h1>Here are my favorite sites</h1>

     <p><strong>Click on a name to go to that page.</strong></p>
                                                                          The text between the a tags is the
     <p><a href = "http://www.kevalnagaria.blogspotcom">Keval</a></p>            anchor for the link.
     <p><a href = "http://www.kevalnagaria.blogspotcom">Nagaria</a></p>

     <p><a href = "">MySite</a></p>

     <p><a href = "http://www.kevalnagaria.blogspotcom">My</a></p>

                                                                           The anchor links to the page that‟s
                         Elements placed between paragraph tags            value is given by the href attribute.
                        will be set apart from other elements on the
                        page with a vertical line before and after it.
                                                     Keval Nagaria                                         36
IMG: Embedding Images
 <IMG SRC="SomeFile.gif" ALT="My Dog"
      WIDTH=400 HEIGHT=300>
    SRC (required)
    ALT (technically required)
    ALIGN (see <BR CLEAR="ALL">)

                    Keval Nagaria       37
Image Alignment Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HEAD><TITLE>Image Alignment</TITLE></HEAD>
<H1 ALIGN="CENTER">Image Alignment</H1>
      <TD><IMG SRC="rude-pc.gif" ALIGN="LEFT"
               ALT="Rude PC" WIDTH=54 HEIGHT=77>
          This positions the image at the left side,
          with text flowing around it on the right.
      <TD><IMG SRC="rude-pc.gif" ALIGN="RIGHT"
               ALT="Rude PC" WIDTH=54 HEIGHT=77>
          This positions the image at the right side,
          with text flowing around it on the left.

                                Keval Nagaria                    38
    <CAPTION>Table Caption</CAPTION>
    <TR><TH>Heading1</TH>      <TH>Heading2</TH></TR>
    <TR><TD>Row1 Col1 Data</TD><TD>Row1 Col2 Data</TD></TR>
    <TR><TD>Row2 Col1 Data</TD><TD>Row2 Col2 Data</TD></TR>
    <TR><TD>Row3 Col1 Data</TD><TD>Row3 Col2 Data</TD></TR>

                         Keval Nagaria                        39
TABLE Element Attributes
     The ALIGN attribute gives the horizontal alignment of the table as
      a whole
     Legal values are LEFT, RIGHT, and CENTER, with LEFT being
      the default
     This specifies the width in pixels of the border around the table
     This is in addition to the border around each cell (the
     The default is zero, which also results in the visible 3D divider
      between cells being turned off
     This gives the space in pixels between adjacent cells. Drawn as a
      3D line if BORDER is nonzero, otherwise empty space in the
      background color is used
     The default is usually about 3

                               Keval Nagaria                               40
    CELLPADDING determines the empty space, in pixels, between
     the cell‟s border and the table element
    The default is usually about 1
    This specifies the width of the table, either in pixels (<TABLE
     WIDTH=250>) or as a percentage of the current browser window
     width (<TABLE WIDTH="75%">)
    Specify the background color of the table TABLE (also legal for
     TR, TD, and TH)
    Non standard attributes supported by IE to specify the colors to
     user for the borders

                              Keval Nagaria                             41
    This nonstandard attribute supported by IE gives an image file that
     will be tiled as the background of the table
    You might want to use style sheets instead.
    HTML 4.0 attribute that specifies which inner dividing lines are
    All are drawn if this attribute is omitted
    Legal values are NONE, ROWS, COLS, and ALL
    Specifies which outer borders are drawn
    All four are drawn if this attribute is omitted
    Legal values are BORDER or BOX (all), VOID (none), ABOVE
     (top), BELOW (bottom), HSIDES (top and bottom, despite the
     somewhat confusing name), VSIDES (left and right), LHS (left),
     and RHS (right)

                              Keval Nagaria                                42
    ALIGN (Values: TOP, BOTTOM)
    An enclosing borderless table may give more flexibility
     than the built-in CAPTION.

                         Keval Nagaria                         43
TR: Table Row
 TR is used to define each row in the table
 Each row will then contain TH and/or TD entries
    ALIGN (legal values LEFT, RIGHT, or CENTER) is used to set
     the default horizontal alignment for table cells
    VALIGN (legal values TOP, MIDDLE, or BOTTOM) is used to
     set the default vertical alignment for table cells
    Sets the color for the table row, overriding any values set for the
     table as a whole via the BGCOLOR attribute of TABLE
    Supported only by Internet Explorer, these specify the colors to use
     for the row borders

                               Keval Nagaria                                44
Table Cells: TH and TD
     COLSPAN defines a heading or cell data entry that
      spans multiple columns

       <TABLE BORDER=1>
       <TR><TH COLSPAN=2>Col 1&2 Heading
             <TH>Col3 Heading
         <TR><TD>Col1 Data
             <TD>Col2 Data
             <TD>Col3 Data

                         Keval Nagaria                    45
    ROWSPAN defines a heading or cell data entry that spans multiple
     rows; similar to COLSPAN
    E.g., the following aligns entries on a decimal point
                  <TD ALIGN="CHAR" CHAR=".">
    Values in pixels only (no percentages officially allowed)
    Use with caution
    Same as for TABLE and TR
                              Keval Nagaria                             46
HTML Hex-Colors
         White                    #FFFFFF
         Red                      #FF0000
         Green                    #00FF00
         Blue                     #0000FF
         Cyan                     #00FFFF
         Yellow                   #FFFF00
         Black                    #000000
         Dim Grev                 #545454
         Forest Green             #238E23
         Grey                     #C0C0C0
         Midnight Blue            #2F2F4F
         Orange                   #FF7F00
         Spring Green             #00FF7F
         Turquoise                #ADEAEA

                  Keval Nagaria             47
Basic HTML - Summary
 A DOCTYPE is required to validate the document
 HTML document should have an enclosing
 HTML element, a HEAD (TITLE is required) and
 Hypertext links, <A HREF="…">
    can be absolute or relative
    A link to a named section is denoted by #section
 Tables are composed of main table element,
 <TABLE>; rows, <TR>; table headers, <TH>;
 and table data, <TD>
    Use BGCOLOR to give background colors to tables,
     rows, or cells
    Use ROWSPAN or COLSPAN to join cells
                         Keval Nagaria                  48

  Keval Nagaria   49
Overview of java script
 The growth of the WWW has resulted
 in a demand for dynamic and
 interactive web sites.
 There are many different kinds of
 scripting languages – JavaScript, …
 This lecture aims at offering in-depth
 knowledge of JavaScript, discussing
 the complexity of scripting and
 studying various common examples.

                Keval Nagaria             50
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 page
 Form validation
 Many others …

                 Keval Nagaria             51
JavaScript Versions
 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

                          Keval Nagaria                52
The Future of JavaScript
 ECMA standard brings JavaScript and Jscript
     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
 It is future-proof, and it is not going to disappear
 in the near future. 

                         Keval Nagaria                  53
A Simple Script
<head> <title>Keval Nagaria…</title> </head>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write(“Welocme to Keval Nagaria‟s world…”);

                                Keval Nagaria          54
Embedding JavaScript

<title>First JavaScript Program</title>
<script language=“JavaScript”

                           Keval Nagaria   55
JavaScript Source File
<script language=“JavaScript”
 SRC – specifies the location of an external script
 TYPE – specifies the scripting language of the
 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
                     Keval Nagaria                    56
Need for a source file
 If the JavaScript code is fairly short, you are
 recommended to include the code in the
 HTML document.
 To add clarity to an HTML document.
 To share JavaScript code across multiple
 HTML documents.
 To help you hide your JavaScript code.
   Spent lot of time for JavaScript coding.
   Viewer can only see the location of the source
    file but not the contents.

                     Keval Nagaria                   57
Hide JavaScript from incompatible browsers

<script language=“JavaScript”>
<!– begin hiding JavaScript
// single-line comment, /* … */ multiple-line comment
End hiding JavaScript -->
Your browser does not support JavaScript.

    Not all browsers support JavaScript.
    E.g. NN1, IE2, character-based lynx.

                            Keval Nagaria               58
JavaScript confusion
JavaScript                             Java
Interpreted by the client-side         Compiled on the server before
computer                               executed on the client machine

Dynamic binding, object references     Static binding, object references
are checked at runtime                 must exist at compile time

No need to declare data types          Data types must be declared
Code is embedded in HTML               Code is not integrated in HTML
Limited by the browser                 Java applications are standalone

Can access browser objects             Java has no access to browser

                                 Keval Nagaria                             59
Using the alert() Method
<script language=“JavaScript”>
         alert(“An alert triggered by JavaScript”);

  It is the easiest methods to use amongst alert(),
  prompt() and confirm().
  You can use it to display textual information to the
  user (simple and concise).
  The user can simply click “OK” to close it.

                            Keval Nagaria                60
Using the confirm() Method
<script language=“JavaScript”>
         confirm(“Are you happy with the class?”);

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

                            Keval Nagaria             61
Using the promat() Method
<script language=“JavaScript”>
         prompt(“What is your student id number?”);
         prompt(“What is your name?”,”No name”);

  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

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

                          Keval Nagaria   63
 JavaScript allows you to declare and use
 variables to store values.
 How to assign a name to a variable?
   Include uppercase and lowercase letters
   Digits from 0 through 9
   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

                     Keval Nagaria                 64
Which one is legal?

 %my_variable                     Illegal
                  Keval Nagaria             65
Variable on-the-fly
<script language=“JavaScript”>
         var id;
         id = prompt(“What is your student id number?”);
         name = prompt(“What is your name?”,”No name”);

  We should use “var” because it is more easy
  to keep track of the variables.
                          Keval Nagaria                    66
Data Types
 JavaScript allows the same variable to contain
 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
     Null: an initial value is assigned
     Undefined: the variable has been created by not yet
      assigned a value
                          Keval Nagaria                     67
Numeric Data Types
 It is an important part of any
 programming language for doing
 arithmetic calculations.
 JavaScript supports:
            A positive or negative number
   Integers:
   with no decimal places.
     Ranged    from –253 to 253
   Floating-pointnumbers: usually written
   in exponential notation.
     3.1415…,    2.0e11

                      Keval Nagaria          68
Integer and Floating-point number example

<script language=“JavaScript”>
       var integerVar = 100;
       var floatingPointVar = 3.0e10;
       // floating-point number 30000000000

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

                Keval Nagaria              70
Boolean value example
<script language=“JavaScript”>
       var result;
       result = (true*10 + false*7);
       alert(“true*10 + false*7 = “, result);

   The expression is converted to
       (1*10 + 0*7) = 10
   They are automatically converted.
                         Keval Nagaria          71
 A string variable can store a sequence
 of alphanumeric characters, spaces and
 special characters.
 String can also be enclosed in single
 quotation marks („) or in double
 quotation marks (“).
 What is the data type of “100”?
   String   but not number type
 Pay attention to the special characters.

                     Keval Nagaria          72
Strings example
<script language=“JavaScript”>
         document.write(“This is a string.”);
         document.write(“This string contains „quote‟.”);
         var myString = “My testing string”;

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

                            Keval Nagaria                   73
typeof operator
<script language=“JavaScript”>
         var x = “hello”, y;
         alert(“Variable x value is “ + typeof(x));
         alert(“Variable y value is “ + typeof(y));
         alert(“Variable x value is “ + typeof(z));

   It is an unary operator.
       Return either: Number, string, Boolean, object,
        function, undefined, null
                             Keval Nagaria                74
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.
     Cars have wheels, dogs have fur.
     Browser has a name and version number.

                           Keval Nagaria                 75
 An Array contains a set of data represented
 by a single variable name.
 Arrays in JavaScript are represented by the
 Array Object, we need to “new Array()” to
 construct this object.
 The first element of the array is “Array[0]”
 until the last one Array[i-1].
 E.g. myArray = new Array(5)
     We have myArray[0,1,2,3,4].

                      Keval Nagaria             76
Array Example
<script language=“JavaScript”>
         Car = new Array(3);
         Car[0] = “Ford”;
         Car[1] = “Toyota”;
         Car[2] = “Honda”;
         document.write(Car[0] + “<br>”);
         document.write(Car[1] + “<br>”);
         document.write(Car[2] + “<br>”);

   You can also declare arrays with variable length.
       arrayName = new Array();
       Length = 0, allows automatic extension of the length.
       Car[9] = “Ford”; Car[99] = “Honda”;

                                Keval Nagaria                   77
Null & Undefined
 An “undefined” value is returned when you
 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” if you want absolutely nothing in it,
 but you just don‟t want it to be “undefined”.

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

                                    Keval Nagaria                79
JavaScript Special Characters
Character           Meaning
\b                  Backspace
\f                  Form feed
\t                  Horizontal tab
\n                  New line
\r                  Carriage return
\\                  Backslash
\‟                  Single quote
\”                  Double quote

              Keval Nagaria           80
 It is a set of literals, variables,
 operators that merge and evaluate to a
 single value.
   Left_operand   operator right_operand
 By using different operators, you can
 create the following expressions.
   Arithmetic, logical
   String and conditional expressions.

                    Keval Nagaria           81
 Arithmetic operators
 Logical operators
 Comparison operators
 String operators
 Bit-wise operators
 Assignment operators
 Conditional operators

                Keval Nagaria   82
    Arithmetic operators
     left_operand “operator” right_operand
Operator      Name                  Description           Example
+             Addition              Adds the operands     3+5
-             Subtraction           Subtracts the right   5-3
                                    operand from the
                                    left operand
*             Multiplication        Multiplies the        3*5
/             Division              Divides the left      30 / 5
                                    operand by the
                                    right operand
%             Modulus               Calculates the        20 % 5

                               Keval Nagaria                        83
Unary Arithmetic Operators
  Binary operators take two operands.
  Unary type operators take only one operand.
  Which one add value first, and then assign value
  to the variable?

Name                              Example
Post Incrementing operator        Counter++
Post Decrementing operator        Counter--
Pre Incrementing operator         ++counter
Pre Decrementing operator         --counter

                             Keval Nagaria           84
Logical operators
     Used to perform Boolean operations on Boolean

Operator       Name                Description        Example
&&             Logical and         Evaluate to “true” 3>2 && 5<2
                                   when both
                                   operands are true
||             Logical or          Evaluate to “true 3>1 || 2>5
                                   when either
                                   operand is true
!              Logical not         Evaluate to “true” 5 != 3
                                   when the
                                   operand is false
                             Keval Nagaria                         85
 Comparison operators
      Used to compare two numerical values
Operator       Name                          Description                      Example

==             Equal                         Perform type conversion          “5” == 5
                                             before checking the equality

===            Strictly equal                No type conversion before        “5” === 5

!=             Not equal                     “true” when both operands        4 != 2
                                             are not equal

!==            Strictly not equal            No type conversion before        5 !== “5”
                                             testing nonequality

>              Greater than                  “true” if left operand is        2>5
                                             greater than right operand

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

>=             Greater than or equal         “true” if left operand is        5 >= 2
                                             greater than or equal to the
                                             right operand

<=             Less than or equal            “true” if left operand is less   5 <= 2
                                             than or equal to the right

                                       Keval Nagaria                                      86
Strict Equality Operators

<script language=“JavaScript”>
          var currentWord=“75”;
          var currentValue=75;
          var outcome1=(currentWord == currentValue);
          var outcome2=(currentWord === currentValue);
          alert(“outcome1: “ + outcome1 + “ : outcome2: “ + outcome2);

  Surprised that outcome1 is True!
  JavaScript tries very hard to resolve
  numeric and string differences.
                              Keval Nagaria                              87
String operator
    JavaScript only supports one string
    operator for joining two strings.

Operator          Name                Description   Return value
+                 String        Joins two           “HelloWorld”
                  concatenation strings

<script language=“JavaScript”>
          var myString = “”;
          myString = “Hello” + “World”;
                                 Keval Nagaria                     88
    Bit Manipulation operators
     Perform operations on the bit representation of a
     value, such as shift left or 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 XOR                     Set the result bit, only if
                                                     either bit is 1, but not both

<<                   Bitwise left shift              Shifts the bits of an
                                                     expression to the left

>>                   Bitwise signed right shift      Shifts the bits to the right,
                                                     and maintains the sign

>>>                  Bitwise zero-fill right shift   Shifts the bits of an
                                                     expression to right

                                Keval Nagaria                                           89
    Assignment operators
     Used to assign values to variables
Operator          Description                      Example
=                 Assigns the value of the right A = 2
                  operand to the left operand
+=                Add the operands and             A += 5
                  assigns the result to the left
-=                Subtracts the operands and       A -= 5
                  assigns the result to the left
*=                Multiplies the operands and      A *= 5
                  assigns the result to the left
/=                Divides the left operands by     A /= 5
                  the right operand and assigns
                  the result to the left operand
%=                Assigns the remainder to the     A %= 2
                  left operand
                              Keval Nagaria                  90
The most common problem
<script language=“JavaScript”>
       if (alpha = beta) { … }
       if (alpha == beta) { … }

   Don‟t mix the comparison operator and the
   assignment operator.
   double equal sign (==) and the equal
   operator (=)

                       Keval Nagaria           91
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             =, +=, -=, *=, …
 15             The comma (,) operator
              Keval Nagaria                         92
Precedence Example
Value =   (19 % 4) / 1 – 1 - !false
Value =   3 / 1 – 1 - !false
Value =   3 / 1 – 1 - true
Value =   3 – 1 - true
Value =   3–2
Value =   1

                 Keval Nagaria        93
Scope of a Variable
 When you use a variable in a
 JavaScript program that uses functions.
 A global scope variable is one that is
 declared outside a function and is
 accessible in any part of your program.
 A local variable is declared inside a
 function and stops existing when the
 function ends.

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

                                                          Keval Nagaria                                              95
Conditional Statement
 “if” statement
 “if … else” statement
 “else if” statement
 “if/if … else” statement
 “switch” statement

               Keval Nagaria   96
“if” statement
    if (condition) { statements; }

 It is the main conditional statement in
 The keyword “if” always appears in
 The condition yields a logical true or false
 The condition is true, statements are
                   Keval Nagaria                97
 “if” statement example

<script language=“JavaScript”>
var chr = “”;
if (chr == „A‟ || chr == „O‟) {
       document.write(“Vowel variable”);

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

                                 Keval Nagaria             98
“if … else” statement

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

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

                  Keval Nagaria              99
 Ternary Shortcut (concise)
<script language=“JavaScript”>
If (3 > 2) {
} else {

(3 > 2) ? alert(“True”) : alert(“False”);

    Substitute for a simple “if/else” statement.
                          Keval Nagaria            100
“else if” statement

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

 Allows you to test for multiple expression
 for one true value and executes a particular
 block of code.

                   Keval Nagaria                101
“if/if…else” statement example
<script language=“JavaScript”>
var chr;
chr = prompt(“Please enter a character : “,””);
if (chr >= „A‟){
   if (chr <= „Z‟)
   else if (chr >= „a‟){

                        Keval Nagaria             102
“switch” statement
    switch (expression) {
          case label1:
                 statements; break;

 Allows you to merge several evaluation
 tests of the same variable into a single block
 of statements.
                    Keval Nagaria                 103
  “switch” statement example
<script language=“JavaScript”>
var chr;
chr = prompt(“Pls enter a character in lowercase:”,””);
         case „a‟ :
                  alert(“Vowel a”); break;
         case „e‟ :
                  alert(“Vowel e”); break;
         default :
                  alert(“Not a vowel”);

                               Keval Nagaria              104
Looping Statement
 “for” Loops
 “for/in” Loops
 “while” Loops
 “do … while” Loops
 “break” statement
 “continue” statement

               Keval Nagaria   105
“for” statement
   for (initial_expression; test_exp; change_exp)
   { statements; }

 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
 The change_exp determines how much has
 been added or subtracted from the counter
                    Keval Nagaria                   106
“for” statement example
<script language=“JavaScript”>
var counter;
for (counter = 1; counter <= 10; counter++)
       document.write(counter*counter + “ “);

   Display the square of numbers
   Output: 1 4 9 16 25 36 49 64 81 100

                        Keval Nagaria           107
“for/in” statement
      for (counter_variable in object)
      { statements; }

 When the for/in statement is used, the counter and
 termination are determined by the length of the
 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

                         Keval Nagaria                 108
 “for/in” statement example
<script language=“JavaScript”>
var book; (What is the difference if “var book=“”;)
var booklist = new Array(“Chinese”, “English”, “Jap”);
for (var counter in booklist) {
       book += booklist[counter] + “ “;

                         Keval Nagaria                   109
“while” statement
    initial value declaration;
    while (condition) {
            increment/decrement statement;

 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
                   Keval Nagaria              110
 “While” statement example
<title>While loop example</title>
<script language=“JavaScript”>
var counter = 100;
var numberlist = “”;
while (counter > 0) {
     numberlist += “Number “ + counter + “<br>”;
     counter -= 10;
</script> <body> … </body>

                              Keval Nagaria        111
“do … while” statement
    do {
           counter increment/decrement;
     } while (termination condition)

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

                    Keval Nagaria                   112
 A function is a block of organized reusable
 code (a set of statements) for performing a
 single or related action.
 Begins with keyword “function” and the
 function name and “( … )”
 Inside the parentheses
   We can pass parameters to the function
   E.g. function myfuc(arg1, arg2) {…}
   Built-in and user-defined functions

                     Keval Nagaria             113
Built-In Functions
 Functions provided by the language and you
 cannot change them to suit your needs.
 Some of the built-in functions in JavaScript are
 shown here:
     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  NaN.
     parseFloat
          Finds a floating-point value at the beginning of a string.
                                Keval Nagaria                           114
User-Defined Functions
  For some functionality, you cannot achieve
  by only using the built-in functions.
  You can define a function as follows

function <function_name> (parameters)
    // code segments;

                   Keval Nagaria               115
Function Declarations
•   Declaration Syntax
       Functions are declared using the function reserved
       The return value is not declared, nor are the types of
        the arguments
       Examples:

         function square(x) { return(x * x); }

         function factorial(n) {
             if (n <= 0) {
             } else {
               return(n * factorial(n - 1));
                             Keval Nagaria                       116
 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)
   We can validate the data entered by a user in a
    web form
   Communicate with Java applets and browser

                      Keval Nagaria                   117
Event Categories
 Keyboard and mouse events
     Capturing a mouse event is simple
 Load events
     The page first appears on the screen: “Loads”, leaves:
      “Unloads”, …
 Form-related events
     onFocus() refers to placing the cursor into the text input
      in the form.
     Errors, window resizing.

                           Keval Nagaria                           118
 Events defined by JavaScript
HTML elements   HTML tags        JavaScript defined events   Description

Link            <a>              click                       Mouse is clicked on a link
                                 dblClick                    Mouse is double-clicked on
                                 mouseDown                   a link
                                 mouseUp                     Mouse button is pressed
                                 mouseOver                   Mouse button is released
                                                             Mouse is moved over a link
Image           <img>            load                        Image is loaded into a
                                 abort                       browser
                                 error                       Image loading is abandoned
                                                             An error occurs during the
                                                             image loading
Area            <area>           mouseOver                   The mouse is moved over
                                 mouseOut                    an image map area
                                 dblClick                    The mouse is moved from
                                                             image map to outside
                                                             The mouse is double-
                                                             clicked on an image map
Form            <form>           submit                      The user submits a form
                                 Reset                       The user refreshes a form
…               …                …                           …

                            Keval Nagaria                                                 119
Event Handlers
 When an event occurs, a code segment is
 executed in response to a specific event is
 called “event handler”.
 Event handler names are quite similar to the
 name of events they handle.
 E.g the event handler for the “click” event is

 <HTMLtag eventhandler=“JavaScript Code”>

                   Keval Nagaria                  120
Event Handlers
Event Handlers         Triggered when
onChange               The value of the text field, textarea,
                       or a drop down list is modified
onClick                A link, an image or a form element
                       is clicked once
onDblClick             The element is double-clicked
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
onResize               A form is resized by the user

                 Keval Nagaria                                  121
onClick event Handler
<title>onClick Event Handler Example</title>
<script language=“JavaScript”>
function warnUser(){ return confirm(“INE2720 students?”); }
<a href=“reference.html”, onClick=“return
   warnUser();”>INE2720 Students access only</a>

                         Keval Nagaria                        122
onLoad event Handler
<title>onLoad and onUnload Event Handler
<body onLoad=“alert(„Welcome User‟);”
onUnload=“alert(„Thanks for visiting the page‟);”>
Load and UnLoad event test.

                       Keval Nagaria                 123
User Events, Form Example
  <title>Simple JavaScript Button</title>
<script language=“JavaScript"><!--
function dontClick() {
   alert("I told you not to click!");
// --></script>

<h1>Simple JavaScript Button</h1>
 <input type=“button"
      value="Don't Click Me"

                                       Keval Nagaria   124
onMouseOver and onMouseOut Event Handlers

<title>onMouseOver and onMouseOut event handler</title>
<a href=“link.html”
onMouseOver = “status = „Now mouse is over the link‟; “
onMouseOut = “status = „Mouse has moved out‟;”>
A Link Page

                          Keval Nagaria                   125
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.

                         varA                   varB

                         varC                   varD

         FunctionA (…)                    FunctionB (…)

         FunctionC (…)                    FunctionD (…)

                                Keval Nagaria                126
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.
     Function-Valued Properties

                            Keval Nagaria              127
Creating Instances of Objects
 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
          objA = new Date()
     Assign another date and time to objB
          objB = new Date(99,23,5)  23 May, 99

                            Keval Nagaria             128
Objects and Classes
•   Fields Can Be Added On-the-Fly
       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
       For instance:

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

                         Keval Nagaria                    129
Objects and Classes – Literal Notation
•   You Can Use Literal Notation
        You can create objects using a shorthand “literal”
         notation of the form

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

        For example, the following gives equivalent values to
         object1 and object2
         var object1 = new Object();
         var object2 = new Object();
         object1.x = 3;
         object1.y = 4;
         object1.z = 5;
         object2 = { x:3, y:4, z:5 };

                               Keval Nagaria                     130
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
    •      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 = y;
                 this.speed = speed;
                 this.direction = direction;

                                 Keval Nagaria                               131
Class Methods, Example
 function degreesToRadians(degrees) {
   return(degrees * Math.PI / 180.0);

  function move() {
    var angle = degreesToRadians(this.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;

                               Keval Nagaria          132
Build-In JavaScript Objects
Object              Description
Array               Creates new array objects
Boolean             Creates new Boolean objects
Date                Retrieves and manipulates dates and
Error               Returns run-time error information
Function            Creates new function objects
Math                Contains methods and properties for
                    performing mathematical
Number              Contains methods and properties for
                    manipulating numbers.
String              Contains methods and properties for
                    manipulating text strings
              Keval Nagaria                               133
Keval Nagaria   134
Keval Nagaria   135

To top