Document Sample
javascript_and_dom Powered By Docstoc
					Website Development

    JavaScript & DOM

    Prepared By :
              What is JavaScript?
   JavaScript is a scripting language (a scripting language is a
    lightweight programming language) designed to enhance
    Web pages
   JavaScript is an interpreted language (means that scripts
    execute without preliminary compilation)
   A JavaScript is usually embedded directly into HTML pages
    or we can import it
   JavaScript has almost nothing to do with Java!
   JavaScript is CasE-sensitive!!! (bgcolor≠bgColor)
   JavaScript statement ends with a semicolon(optional)
                    Why JavaScript?
   Introduce high level of interactivity to your Web site
   Relatively easy to learn
   Almost All browsers support JavaScript like Internet
    Explorer, Mozilla, Mozilla Firefox, Netscape, Opera, and more
   Lots of scripts are available on-line for FREE!
                     Basic Concepts
   JavaScript is an object-oriented, event-driven language.
      An event is something occurs to an object.
      (e.g., clicking on a link, moving mouse cursor, etc.)
   In the context of a web page, JavaScript objects are HTML elements.
   Objects have properties, and properties have values.
   The JavaScript code that handles events is called event handler
    (onMouseOver, onMouseOut, onLoad, onSubmit, onClick, etc.).
   It starts with <script language=“javascript”> and ends with </script>

   To hide the code from old browsers   <!--      //-->
    is used
             Data Type, Variable
   The Primitive Data types That JavaScript Supports
       Number (10, 23.34, -45.6, 2E3, 0X5F)
       Boolean (true, false)
       String (“Hello” , ’45’, “java script”)
       Null (empty)
   Syntax to Declare Variable
       var <variable name>=value;
   typeof keyword can be used to identify type of variable
       (var a=10; typeof a will give number)
   Convert String to Number
       parseInt(varname), parseFloat(varname)
   Convert Number to String
       Varname.toString()
                   Array & Operators
   Array Declaration Syntax
       array1=new Array(10); (index from 0 to 9)
       length property gives Number of elements of Array
       join(“<separator>”) method joins the elements of the
        array to a string
       sort() method sorts the elements of the array
   Arithmetic                     String Operator
       +,-,*,/,%,++,--               +
   Logical                        Assignment Operator
       &&,||,!                       =,+=,-=,*=,/=,%=
   Comparison Operator            Conditional Operator
       ==,!=,<,>,<=,>=               ? :
                                   Special Operator
                                      new , delete,
                      Control Statements
Statement          Purpose                                               Example
Assignment         Assigns the value of an expression to a variable      x=y+z

Data declaration   Declares a variable and optionally assigns a value    var myVar=10
                   to it
if                 Program execution depends upon the value of           if(x<y)
                   returned by the condition. If the value returned is   {
                   true then program executes else the program does           z=x;
                   not execute.                                          }
switch             Selects from a number of alternatives                 switch(val)
                                                                             case 1:
                                                                             case 2:
            Control Statements (Cont..)
while               Repeatedly executes a set of statements until a   x=1;
                       condition becomes false                        while(x!=20)
for                 Repeatedly executes a set of statements until a   for(x=1;x!=20;x++)
                       condition becomes false                        {
do while            Repeatedly executes a set of statements until a   do
                       condition becomes false                        {
break               Immediately terminates a do, while or for block   If(x>y) break;

continue            Immediately terminates the current iteration of   If(x>y) continue;
                       a do, while or for block
return              Returns a value from a function                   return x*y
Function call       Invokes a function                                x=abs(y)
Method invocation   Invokes a method of an object                     document.write(“Hello
   Functions are declared through keyword function
   Syntax of function declaration
       function <function name>(parameter)
           return value;
   Calling a function
       myVar=<function name> (argument);
       Builtin javascript Objects
   Math Object
   String Object
   Date Object
        Math Object
Method Name    Example           Returned Value

abs            Math.abs(-79)     79

acos           Math.acos(.5)     1.047197551196597631

asin           Math.asin(1)      1.570796326794896558

atan           Math.atan(.5)     0.4636476090008060935

ceil           Math.ceil(7.6)    8

cos            Math.cos(.4)      0.9210609940028851028

exp            Math.exp(8)       2980.957987041728302

floor          Math.floor(8.9)   8
         Math Object Cont…
Method Name     Example                 Returned Value

log             Math.log(5)             1.609437912434100282

max             Math.max(1 , 700)       700

min             Math .min(1 , 700)      1

pow             Math.pow(6,2)           36

random          Math.random()           .7877896 (not fully

round           Math.round(.567)        1

sin             Math.sin(Math.PI)       0

sqrt            Math.sqrt(9801)         99

tan             Math.tan(1.5*Math.PI)   INF (infinity)
          String Object
  MethodName                     Example            Returned Value
anchor          "foo".anchor("anchortext")   <A NAME="anchortext">foo</A>
big             "foo".big()                  <BIG>foo</BIG>
blink           "foo".blink()                <BLINK>foo</BLINK>
bold            "foo".bold()                 <B>foo</B>
fixed           "foo".fixed()                <TT>foo</TT>
fontcolor       "foo".fontcolor("green")     <FONT COLOR="green">foo</
fontsize        "foo".fontsize(-1)           <FONT SIZE="-1">foo</FONT>
italics         "foo".italics()              <I>foo</I>
link            "foo".link("linktext")       <A HREF="linktext">foo</A>
small           "foo".small()                <SMALL>foo</SMALL>
strike          "foo".strike()               <STRIKE>foo</STRIKE>
sub             "foo".sub()                  <SUB>foo</SUB>
sup             "foo".sup()                  <SUP>foo</SUP>
toLowerCase     "UPPERcase".toLowerCase()    uppercase
toUpperCase     "UPPERcase".toUpperCase()    UPPERCASE
          Date Object
 var today = new Date(); or var today=new Date(year, month, day, hours, minutes, seconds)

Method                       Example                         Returns
getDate                      today.getDate()                 5
getDay                       yesterday.getDay()              2
getHours                     today.getHours()                5
getMinutes                   today.getMinutes()              30
getMonth                     year.getMonth()                 6
getSeconds                   time.getSeconds()               13
getTime                      now.getTime()                   *****
getTimeZoneoffset            today.getTimeZoneoffset         ******
getYear                      now.getYear                     96 (the years since 1900)
parse                        Date.parse(July 1, 1996)        *****
          Date Object Cont…
Method             Example                   Returns
setDate            now.setDate(6)            -
setHours           now.setHours(14)          -
setMinutes         now.setMinutes(50)        -
setMonth           today.setMonth(7)         -
setSeconds         today.setSeconds(7)       -
setTime            today.setTime             -
setYear            today.setYear(88)         -
toGMTString        yesterday.toGMTString()   Sat, Feb 24 1996
                                             14:28:15 GMT
toLocaleString     today.toLocaleString()    2/25/96 14:28:15
UTC                Date.UTC(96,11,3,0,0,0) -
             JavaScript and DOM
   JavaScript relies on a Document Object Model
    (DOM) that describes the structure of the web
       This is not the same as the XML DOM
   You can do a lot with a just a little understanding
    of the DOM
       You use the DOM to access elements on the web page
       You can capture events without knowing the DOM at all
       You need the DOM to make any changes to the web
   The                                                 plugins[]               Mime types[]
                                                 Array of plugin objects   Array of mime objects

                                                     mime types[]
hierarchy                    self, window,
                              parent, top
                                                 Array of mime objects
                        Various window objects
                                                       forms []                  elements[]
                                                 Array of form objects     Array of HTML form
   The Current Window

                             navigator                                        element objects
                          Navigator objects                                        Button
                                                 Array of anchor objects         Checkbox
                             frames []                                           Fileupload
                          Array of window                                         Hidden
                               objects                  links[]
                                                  Array of link objects
                             location                                               Radio
                          Location objects                                          Reset
                                                       images[]                     select
                                                 Array of image objects            Submit
                           History objects                                           Text
                                                        applets[]                 Textarea
                           document                   Array of
                         Document objects        javaobjects objects
                              package                 embeds[]                  options[]
                        Java package objects      Array of javaobjects       Array of option
                                                        objects                  objects
                 window object
 Properties                    Methods
•Frames                    alert(message)
•length                    close()
•Name                      confirm(message)
•Parent                    open(url,name,features)
•Self                      prompt(message,response)
•window                    clearTimeout(name)
             navigator object
Properties                 Methods
•appCodeName               javaEnabled()
               document object
A document (i.e. the HTML page) can contain various HTML objects

  •Multimedia Objects
  •Form with various form elements
Property       Description
alinkColor     The RGB value for the color of activated links expressed as a hexadecimal
anchors        Array of objects corresponding to each named anchor in a document.
applets        Array of objects corresponding to each Java applet included in a document.
bgColor        The RGB value of the background color as a hexadecimal triplet.
cookie         Contains the value of the cookies for the current document.
embeds         Array of objects reflecting each plug-in in a document.
fgColor        The RGB value of the foreground color as a hexadecimal triplet.
forms          Array of objects corresponding to each form in a document.
images         Array of objects corresponding to each in-line image included in a
lastModified   A string containing the last date the document was modified.
linkColor      The RGB value of links as a hexadecimal triplet.
links           An array of objects corresponding to each link in a document. Links
                can be hypertext links or clickable areas of an imagemap.
location        The full URL of the document. This is the same as the URL property.
                URL should be used instead of location.
referrer        Contains the URL of the document that called the current document.
title           A string containing the title of the document.
URL             The full URL of the document.
vlinkColor      The RGB value of followed links as a hexadecimal triplet.

open(), close(), and clear().
                        Form Processing
   A form contains the elements
       Text Box         Administrator                <input type=“text” name=“t1”>
       Password Box     *******                      <input type=“password” name=“p1”>
       Radio Button                                        <input type=“radio” name=“r1”>
       Check Box        Read        Write           <input type=“checkbox” name=“c1”>
       Combo Box        Sem1                        <select name=“s1”>
       List Box

       Text Area       gfhfgg
                                                            <textarea row=“10 col=“40”>

       Submit Button       Submit           <input type=“submit” name=“submit” value=“Submit”>
       Reset Button
                            Reset            <input type=“reset” name=“reset” value=“raset”>
Thank You…

Shared By: