Docstoc

JavaScript

Document Sample
JavaScript Powered By Docstoc
					Programming
    With
 JavaScript
                  Objectives
Define JavaScript
Differentiate between client-side and server-
 side scripting
Define object-based language
Define object, property, method, and event
Explain the Object Hierarchy
Use event handlers and functions
Create XHTML documents using JavaScript
Create and link to an external JavaScript file
                  JavaScript
Scripting language
It is interpreted line-by-line.
Has keywords and syntax.
An object-base language.
Developed by Netscape as LiveScript.
ECMAScript became international
 standard
Will be using ECMAScript 3rd Edition
   Two Scripting Models

Client-Side
 Processed by the browser




                Server-Side
                  Processed by the server
   Client-Server Architecture
Two Tier               Three Tier
  Client (Front End)     Client
  Server (Back End)      Processing
                          Data Storage
Two Computers          Two or More Computers
                          Data Storage is conceptual
                          Can be on same computer as
                           processing
Client-Side Scripts
 Client-side scripts Characteristics
    XHTML document
    Interpreted by the browser
    Can perform many functions such as data validation
      and providing interactive feedback to the user
 Client-side Scripting Advantages
    Client has to make fewer trips to the server for
      information
    Users are allowed to interact with the Web page
    Scripts are able to respond to user events
 Client-side Scripting Disadvantages
    The browser must support the scripting language
        • Some browsers not support VBScript
    Scripts may have different results in different browsers
Server-Side Scripts
 Server-side Script Characteristics
   Not embedded into an XHTML
   Stored and run on a Web server
 Server-side Advantages
   Ability to interact with a relational database
   Perform file manipulations on the server
   Generate responses based on users’ requests
   No problems with browser support
   Only the XHTML is sent to the client
   Script execution is hidden from the user
   Can’t see password or charge card number
 Server-side Disadvantages
   More burden is placed on the Web server
   Increased network traffic
   Possible decrease in execution speed
                        Background
                        Definitions
 Literal
    Fixed value
       price = 5.00 -1.00
 Variable
    Symbol or name that represents a value
       cost = 5.00
       discount = 1.00
       price = cost - discount
 Function
    Named group of programming statements
        function greetings( ) {
           document.write(“Hello”);
           document.write(“Good Bye”);
           }
               Object
 Set of related Methods and Properties
          that can be compartmentalized



          Methods        Properties




                  Object

Examples of Objects: Window, Document, Form
              Methods
 One or more programming statements
 Function that is called from an object
 Naming Convention:
      uses a verb to denote action
 Examples
       document.write
       window.open
       history.go
               Property
 Variable whose value can change
 Considered data of the objects
 Can be assigned values for each object
 Naming Convention:
   uses a noun to denote attribute
 Examples
   document.bgColor
   form.name
   window.status
                  Events
 Actions that can trigger other functions
 Event handlers react to specific events
 Examples
  onclick
  onmouseover
  onfocus
  onload
       Object (Review)
Set of related Methods and Properties
         that can be compartmentalized



         Method         Properties




                 Object

Objects can also have related Events
                      JavaScript Object
                           Model
                                    Window




  Navigator        Location        Document     History   Frame

         …                                  …
 • All objects except Window are contained in a parent object
 • Some objects will also contain children objects


Click on an object to see its definition.                   Next Slide
                    Window Object
  This object is at the top of the browser object hierarchy and
             refers to the current browser window.
       Properties               Methods                             Events
          defaultStatus               alert()                        onBlur
          document                    blur()                         onError
          frames[]
                                       clearTimeout()                 onFocus
          history
                                       close()                        onLoad
          location
                                       confirm()                      onResize
          name
          opener                      focus()                        onUnload
          parent                      open()
          self                        prompt()
          status                      setTimeout()
          top                               Window
          window
                 Navigator    Location      Document         History          Frame
                             (Click for Properties, Methods, and/or Events,
Back
                                        Click on Back when done)
                      JavaScript Object
                           Model
                                    Window




  Navigator        Location        Document     History   Frame

         …                                  …
 • All objects except Window are contained in a parent object
 • Some objects will also contain children objects


Click on an object to see its definition.                   Next Slide
               Navigator Object
          Used to obtain information about the current
                          Web Browser

       Properties                              Methods
         appCodeName                                 javaEnabled()
         appName
         appVersion
         language
         platform
         userAgent
                                             Window



              Navigator      Location       Document         History       Frame


                          (Click for Properties, Methods, and/or Events,
                                     Click on Back when done)
Back
                      JavaScript Object
                           Model
                                    Window




  Navigator        Location        Document     History   Frame

         …                                  …
 • All objects except Window are contained in a parent object
 • Some objects will also contain children objects


Click on an object to see its definition.                   Next Slide
                    Location Object
   Contains information about the current document such as URL,
  path, and domain name. Allows the user to change to a new web
                 page from within JavaScript code.
         Properties                              Methods
             hash                                    reload()
             host                                    replace()
             hostname
             href
             pathname
             port
             protocol
                                      Window
             search

            Navigator   Location     Document         History         Frame
                         (Click for Properties, Methods, and/or Events,
Back                                Click on Back when done)
                      JavaScript Object
                           Model
                                    Window




  Navigator        Location        Document     History   Frame

         …                                  …
 • All objects except Window are contained in a parent object
 • Some objects will also contain children objects


Click on an object to see its definition.                   Next Slide
                     Document Object
           The body of the current XHTML document, which is
                 displayed within the browser window.

Properties                                 Methods                     Event Handlers
        alinkColor      forms                  close                     onClick
        anchors[]       images                 open                      onDblClick
        applets[]       lastModified           write                     onKeyDown
        bgColor         linkColor              writeln                   onKeyPress
        cookie          links[]                                           onMouseDown
                         referrer
        domain                                                             onMouseUp
                         title
        embeds[]
                         URL
        fgcolor
        vlinkColor                          Window



             Navigator       Location       Document         History        Frame

                          (Click for Properties, Methods, and/or Events,
Back                                 Click on Back when done)
                      JavaScript Object
                           Model
                                    Window




  Navigator        Location        Document     History   Frame

         …                                  …
 • All objects except Window are contained in a parent object
 • Some objects will also contain children objects


Click on an object to see its definition.                   Next Slide
                        History Object
        Maintains the record of all the documents that have
       been opened during the current Web browser session.

         Properties                                Methods
              length                                    back
                                                         forward
                                                         go


                                        Window



         Navigator       Location      Document         History       Frame


                     (Click for Properties, Methods, and/or Events,
                                Click on Back when done)

Back
                      JavaScript Object
                           Model
                                    Window




  Navigator        Location        Document     History   Frame

         …                                  …
 • All objects except Window are contained in a parent object
 • Some objects will also contain children objects


Click on an object to see its definition.                   Next Slide
                        Frame Object
       Contains information about the current document such as URL,
                          path, and domain name.


       Properties                   Methods                        Events
         action                           reset()                      onReset
         method                           submit()                     onSubmit
         enctype
         target
         name
         elements[]
                                               Window
         length

                Navigator       Location      Document         History       Frame


                            (Click for Properties, Methods, and/or Events,
Back                                   Click on Back when done)
                      JavaScript Object
                           Model
                                    Window




  Navigator        Location        Document     History   Frame

         …                                  …
 • All objects except Window are contained in a parent object
 • Some objects will also contain children objects


Click on an object to see its definition.                   Next Slide
                             Form Object
   (Notice we have moved down a level in the hierarchy)
Properties                  Methods                    Events
       action                      reset()                      onAbort      onKeyPress
       method                      submit()                     onBlur       onKeyUp
       enctype                                                   onClick      onLoad
       target                                                    onDragDrop   onMouseDown
       name                                                      onError      onMouseMove
       elements[]                                                OnFocus      onMouseOut
       length                                                    onKeydown    onMouseOver
                                                                                onMouseUp
                                  Window                                        onReset
                                                                                onResize
Navigator       Location          Document           History           Frame    onSelect
                                                                                onSubmit
                                                                                onUnload
            …              Form              Image                 …
             Objects in a Form
              (Typical Items…Will Vary by Object)
Properties                    Methods                                  Events
                                      blur                                   click
  align
                                      focus                                  onClick
  value                                                                      onLoad
                                      select
  defaultvalue                                                               onBlur
  form                                                                       onFocus

  maxLength                                         Window


  name
             Navigator           Location          Document            History       Frame
  size
  SRC
                          …                 Form              Image              …
  type

             …           Input              Select            Button             …
              Image Object
Properties                    Methods                              Events
  border                        reset()                               onAbort
  complete                      submit()                              onLoad
  height                                                               onError
  hspace
  lowsrc                                       Window
  name
  src        Navigator       Location          Document           History       Frame

  vspace
  width                  …              Form              Image             …
           Document Object Model
                                               Window

                                                   Document

                                                     Anchor[ ]

                                                      Area[ ]

                                                     Image[ ]

                                                      Link[ ]

                                                     Plugin[ ]

                                                     Applet[ ]

                                                      Form[ ]

Textarea   Text   FileUpload   Password   Hidden      Submit     Reset   Radio   Checkbox   Button     Select


     Document, Form, and Select have child objects                                                  Options[ ]



    Some objects contain multiple child objects within a parent
    Multiple objects can be reference by index number or name
    Method and properties are not included in this chart
       So, why do I care?
 It will be on the test!
 You can impress friends
  and colleagues with your
  knowledge!
 It will give you a better
  understanding of the overall
  process.
 In code, may need to reference
  a particular object
           window.alert
window.document.FormName.FieldName
        Note: If the code is on the same form as the object,
              window and document are not needed.
              JavaScript Syntax
 Property
   document.bgColor = “red”

 Method
   document.write (“JavaScript Jive”)

 Event Handler
   <input type="button" value="Say Hi"
      name="btnAlert" id="btnAlert"
      onmousedown=“window.alert(‘Hi’)”
   />
JavaScript is case sensitive, the wrong case will cause errors.
  If quotes are inside of quotes, they must be alternated
             between single and double quotes.
               “window.alert(‘Hi’)”
                 Properties (Review)
Object   Property        Property Description
window    status         sets the message displayed in the status bar.
          length         contains the number of frames in the window.
document bgColor         specifies the background color of the current document.
          fgColor        specifies the color of the text on the document.
          lastModified   specifies the date when the document was last modified.
          title          specifies the title of the document.
          linkColor      specifies the color of the links on the document.
history  length          contains the number entries in the history list.
          current        specifies the URL of the current history entry.
          next           specifies the URL of the next entry in the history list.
          previous       specifies the URL of the previous entry in the history list.
location  hostname       will specify the hostname of the server.
form      name           specifies the name of the form.
          method         specifies how the input information sent to the server.
          action         specifies the destination for the data submitted from form
             Methods (Review)
Object     Method    Description

window     alert     Displays an alert dialog box.
           open      Opens a new browser window.
document   write     Write text and XHTML elements to the
                         current document.
           writeln   Write text and XHTML elements to the
                         current document. It also adds a line.
history    go        Loads a URL from history.
           back      Returns to the previous URL in the history list
           forward   This method will load the next URL in the
                          history list
              Events (Review)
Event         Description
onclick       Some action will be performed when
                       any mouse button is clicked.
onload        Some action is performed when the
                        document is loaded.
onmouseover   Some action is performed when the mouse
                       is moved over something.
onresize      Some action is performed when a page or
                       element is resized.
onfocus       Some action is performed when a particular
                        element gets focus.
onkeydown     Some action is performed when a key is depressed.
onkeypress    Some action is performed when a key is depressed
                       and the associated code is available.
onkeyup       Some action is performed when a key goes up.
onblur        Some action is performed when a particular element
              loses focus.
          JavaScript
        Implementation
 Using an event handler

Embedding the script using a
   <script> </script> tags

 Using a link to an external file
  (source file - .js) that contains a script
                        Event Handler
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
      <title>Event Handler</title>
  </head>
  <body>
     <form method="get" action="formhandler.asp"
           name="frmAlert" id="frmAlert">
         <input type="button" value="Say Hi" name="btnAlert" id="btnAlert"
             onmousedown=‘window.alert(“Hi”)’/>
    </form>
  </body>
</html>
              Embed in Script Tags
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
     <title>Embedded JavaScript</title>
  </head>
  <body>
      <script type="text/javascript" language=“JavaScript">
                <!--
                       window.alert ('This is embedded code');
                 // -->
       </script>
    </body>
</html>
                       Validation
 HTML Containing Scripts
     Treats as CDATA – Character Data
     Portion of the document that is not interpreted as markup
     HTML will validate
 XHTML Containing Scripts
     Treats as PCDATA – Parsed Character Data
     XHTML will not validate
 Alternatives
     Move code to a source file (.js)
     Create a CDATA section
     <script type="text/javascript“ language=“JavaScript">
              //<![CDATA[
                    window.alert ('This is embedded code');
              //]]>
      </script>
                  Multiple JavaScripts
                       - Priority

Browser executes the <script> elements
   1st <head> section
   2nd <body> section
      If within the <body> section, there are
       multiple <script> </script> tags
      Executed in the order they appear.
       Order of Execution
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head><title>Order of Script Execution</title>
       <!-- Script Number 1 -->
       <script language="JavaScript" >
                document.write("Executes First");
       </script>
  </head><body>
       <!-- Script Number 2 -->
       <script language="JavaScript" >
                document.write("Executes Second");
       </script>
       <!-- Script Number 3 -->
       <script language="JavaScript" >
                document.write("Executes Third");
       </script>
  </body></html>
              Link to a Script File
    datDay = new Date();
    document.write(datDay);        sample.js


<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
   <title>Event Handler</title>
           <script language="JavaScript"
               type="text/JavaScript" src="sample.js">
             </script>
  </head>
  <body>
     <h1>Linked .js File</h1>
  </body>
</html>

                                today.htm
    JavaScript Comments
    Comments can help developer and maintainer
      understand what is the purpose of the code.


// This comment is on a single line

/* This comment is on multiple lines.
   I can write as much as needed as
   long as it is terminated properly. */
            JavaScript Functions
 A set of instructions used to perform a task.

 A function contains:
      Function keyword
      Function name
      Parameters (optional)
      Set of code statements

 It must be invoked/called before its code can be
    executed.
function FunctionName(Parameters){
           JavaScript Statements
        }
                Use of a Function
<input type = "button" name = "btnName“ id=“btnName”
      value = "Click Here for Help"
      onClick = “GetName( )"; />



<script type=“text/javascript” language=“JavaScript” >
       function GetName( ) {
             strName=window.prompt(“Enter your name");
            document.write(strName);
                    }
</script>

      Notice the use of ; at the end of each action statement
  Function: Passing Parameters
<form id=“frmName” name=“frmName”>
   <input type = “text" name = “txtName“ id=“txtName” />
   <input type = "button" name = "btnName“ id=“btnName”
        value = “Display Message"
        onClick = “DisplayName(frmName.txtName.value
   )"; />

 <script type=“text/javascript” language=“JavaScript” >
          function DisplayName(strName) {
                window.alert(strName);
                }
 </script>
The value property will reflect the contents of the textbox, listbox,
  textareas, or checkboxes.
 To reference an element on a form the syntax is
           FormName.ElementName.value
              frmName.txtName.value
Other values (i.e. variables, literals) may also be passed as parameters
                    Concatenation
 Appending values to make one value
 JavaScript used + as the concatenation operator

   <script type=“text/javascript” language=“JavaScript” >
            function DisplayName(strName) {
                window.alert(“Hello, “ + strName);
                }
   </script>




Note: JavaScript Guru was entered in the textbox and passed as a
             parameter to the DisplayName function
The End

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:2
posted:1/23/2013
language:Unknown
pages:48