DOM by qingyunliuliu

VIEWS: 12 PAGES: 47

									Standard based web design

 Overview of Dynamic HTML




                            1
        What is DHTML?
Dynamic Hypertext Markup Language is
 comprised of:
       CSS (cascading style sheets)
       DOM (document object module)
       Scripting (Javascript and VBscript)
   Allows for more interactivity and special
    effects on web pages.

                                                2
     Document Object Model (DOM)
   DOM is an interface that permits scripts to access
    and update the content, structure and style of
    the document.
   Every element of the web page can be
    dynamically updated in response to input from the
    user or other programs
   HTML elements are treated as objects, their
    attributes are treated as properties of the objects
   The DOM has a hierarchy of elements with the
    window as the top level object

                                                     3
Object hierarchy: an example




window.document.formName

document.formName
       JavaScript
   JavaScript is an object-based language: it is
    based on manipulating objects by modifying their
    properties or applying methods to them.
   Objects are items that exist in a defined space in a
    Web page (window, document, form etc)
   Each object has properties that describe its
    appearance, purpose, or behavior
   An object can have methods, which are actions
    that can be performed with or to it.
                                                     5
     JavaScript and events
   Certain objects and tags in HTML have
    corresponding events associated to them.
       A button in a form can be clicked
   JavaScript allows you to trigger action
    based on an event taking place, by using
    event handlers
       onClick do this and that


                                               6
        JavaScript and HTML
   Place JavaScript commands in a separate file & link
    the HTML file to that file by using the <SCRIPT> tag in the
    head of the file
    <SCRIPT SRC=URL LANGUAGE=“javascript”>
           other script commands and comments
    </SCRIPT>
 Place JavaScript commands directly in the HTML file
(<SCRIPT> tag in the <HEAD> or the <BODY>)
    <SCRIPT LANGUAGE=“JavaScript”>
      <!- - Hide this script from browsers that don‟t support JavaScript
            script commands and comments
      // Stop hiding from other browsers - ->
    </SCRIPT>                                                              7
    A trivial example
   document.lastModified reflects
    when the page was last modified

    document is the object
    lastModified is a property of document

    <script languange=“javaScript”>
    var modifiedDate=document.lastModified;
    document.write(modifiedDate);
    </script>

                                              8
        The window object and methods
   The window object represents a browser window.
    Window methods are
       window.alert("string“); Shows an alert window
        with text string, and 'OK' button
       window.prompt(“string of character”, “default
        value”); Prompts user for input
       Window.confirm(“string”);If the OK button is
        clicked, the confirm method returns the value “true”
       window.close();
       window.open(URL, windowname);
                                                           9
Objects and their methods




                            11
      JavaScript events
   An event is a specific action that triggers
    the browser to run a block of JavaScript
    commands




                                                  13
Event handlers
       Working with object properties
   Change the value of a property
    object.property = expression
    document.bgColor=“red”
   Save object property as a variable
    variable = object.property
    pageColor =document.bgColor


                                         15
        JavaScript event handlers
    An event handler is code added to an HTML
     tag. It is triggered when the associated
     event occurs within the tag

<TAG event_handler =“JavaScript commands;”>

<FORM>
<INPUT TYPE=RADIO onClick=“document.bgColor=„red‟;”>red<BR>
<INPUT TYPE=RADIO onClick=“document.bgColor=„blue‟;”>blue<BR>
</FORM>

INPUT is the tag, onClick is the event, “document…” is the event handler
                                                                       16
      Coming up
   Form validation
   Mathematical manipulations
   Changing style: visibility,display,clip (menus)
   Repeating commands (Slide shows, banners)
   Filters and transitions
   Moving object on the screen


                                                17
    Validating forms
You can use JavaScript to
 Make sure that your form contain valid
  information
 Check data in one field against data in

  another field (choose a new password)
 Highlight incorrect information to let the

  user know what needs to be changed

                                               18
Form Validation
                                           •If passwd1 ==“”
                                           tell the user to enter a
                                           password and reposition the
                                           cursor to the correct field
                                           •If passwd1!=passwd2
                                           tell the user the 2 passwords
                                           don‟t match and reposition
                                           the cursor

<FORM NAME=“changePsw”    onSubmit=“return checkform(this)”   >
Your name: <INPUT TYPE="TEXT" SIZE="30">
<P>Choose a password: <INPUT TYPE="PASSWORD" NAME="passwd1">
<P>Verify password: <INPUT TYPE="PASSWORD" NAME="passwd2">
<P><INPUT TYPE="SUBMIT" VALUE="Submit"> <INPUT TYPE="RESET">
</FORM>
function validForm(passForm) {
 if (passForm.passwd1.value == "") {
             alert("You must enter a password");
             passForm.passwd1.focus();
             return false}
    else {
       if (passForm.passwd1.value != passForm.passwd2.value) {
              alert("Entered passwords did not match");

              passForm.passwd1.focus();    //return the cursor to the first password field

              passForm.passwd1.select();   //select the entry in the first password field

              return false}
         else {return true}
     }
}

<FORM NAME="changePsw" onSubmit="return validForm(changePsw)" >


or       <FORM onSubmit="return validForm(this)" >
More on forms
   Copying the values entered in one field
    to another field
   Convert F degrees into Celsius
   A mortgage calculator




                                         21
           Microsoft Object Hierarchy
  window

               document                       all

                frames         document     anchors

                history        document     applets

               navigator                     body
                               plugins
               location                     embeds

                 event                      filters

                screen                       forms

                           Only in IE       images

                                             links
Key

      object                                plugins

  collection                                scripts

                                          styleSheets
Netscape DOM
    Element collections
 In JS you translate this hierarchy into
  reference names which indicate the
  location of the element in the DOM
 Elements can be grouped into element
  collections which are arrays of all the
  elements of a particular type
document.images.myImageID.property
document.images[“myImageID”].property

                                            24
      Referencing <DIV> tags
Netscape (<div>s belong to the layers collection)
document.layers.divID or document.divID
I.E. (<div>s belong to the all collection)
document.all.divID or divID
Browser detection:
var isNS=false; // True if user has Netscape
var isIE=false; // True if user has Internet Explorer
if (document.layers){isNS=true;}
if (document.all){isIE=true;}
                                                        25
    Referencing Styles
The syntax rules for changing one of the style
   attributes of an element in
Netscape: objectID.attribute
I.E.           objectID.style.attribute
 objectID is the name of the particular element
   (image, div, form field ..), style is a JS word,
   attribute is the specific attribute you are referring
   to (visibility, display …)
 The attribute can‟t contain “-”!
   background-color becomes backgroundColor
                                                      26
     W3C DOM (a farewell to DOM)
   The W3C DOM doesn‟t use the dot syntax to
    describe objects
   The programmers uses the ID attribute (instead
    of NAME) to name each element in advance
    <IMG ID=myImage>
   Use the getElementByID(tagID) tool to access
    that element
     document.getElementByID(“myImage”)
   Netscape 6, IE 5+, Opera 5+ etc

                                                27
      Controlling object visibility
Internet Explorer
document.getElementById(“id”).visibility=“visible/hidden”;
document.getElementById(“id”).display=“none”;
document.getElementById(“id”).display=“block”;
document.getElementById(“id”).clip=“rect(t,r,b,l)”;




                                                             28
Before clipping




After clipping
Menus
   Side menu: MSNBC
               MetraRail
   Drop Down: T-Mobile
               In-Style Magazine




                                   30
Rollovers
   DePaul website
   Bloomingdale‟s wedding channel
   CBS




                                     31
     Repeating commands
 variable=setInterval(“fctName()”,# of millisec);
tells the script to run the function fctName at the
specified interval of milliseconds.

 clearInterval (variable);
 Cancels the setInterval command



                                                      32
    Time delayed commands
variable= setTimeout(“fctName()”,# of millisec);
tells the script to run the function fctName after the
  specified number of milliseconds

clearTimeout (variable);
Cancels the time delayed command



                                                   33
      Cycling banner ads (images)
adImages is an array containing the URLs of the
  banner images
adBanner is the name in the <IMG> tag where the
  ads are displayed
function next(){…
  document.adBanner.src=adImages[counter];
  setTimeout(“rotate()”,3*1000);…}

Every 3 seconds the src of the image tag is updated
                                                  34
Photo gallery and slide shows
   Prev-Next: Chicago tribune
   Automatic show: MSNBC




                                 35
Other effects
   Scrolling news: metrarail
   Filters
   Increasing font size
   Cursor Images




                                36
        Transition (special filters)
   A transition is a visual effect applied to an object
    over an interval of time
   blendTrans fades an object in and out. You have to
    specify a value for the Duration of the transition
    objectName.filters.blendTrans.Duration =2;
                           or
    objectName.style.filter=“blendTrans(Duration=2)”;
   revealTrans in addition to the Duration it allows you
    to specify the type of the transition
                                                      37
objectName.filters.revealTrans.Duration=2;       // 2 seconds
objectName.filters.revealTrans.Transition=5; //Wipe down
                     or
objectName.style.filter=“revealTrans(Duration=2, Transition=5)”;
Applying a transition
1.   Set the initial state of the object
     (visibility, or source for an image file)
2.   Apply a transition effect to the object
     (by using the apply() method)
     objectName.filters.transition_type.apply();
3.   Specify the final state of the object
4.   Play the transition (use the play() method)
      objectName.filters.transition_type.play();

                                              39
Moving objects on the screen
 Once an object is positioned in the HTML
  code using the position attribute in CSS, you
  can change the coordinates of the object
  using JavaScript attributes
objectID.style.left or objectID.style.top
  how far the left/top edge of the object is
  from the parent element (100px).
  The value of these attributes may be changed
  dynamically

                                            40
function moveObjectTo(objectID,x,y){
  moverObject=document.getElementById(objectID).style;
  moverObject.left =x;
  moverObject.top =y;   }

<IMG id=“mover”
onClick=“moveObjectTo(mover,100,100)>
Moving objects on the screen




function slide(){
  moverObject =document.getElementById(“mover”).style;
  moverObject.pixelLeft =moverObject.pixelLeft +2;
  if (moverObject.pixelLeft <= rightDotPos){
     setTimeout(“slide()”, 20);}

<BODY onLoad=“slide()”>
<IMG ID=“mover” src=fullmoon.jpg>
Window height and width
IE: document.body.clientHeight
    document.body.clientWidth
Are the body properties that indicates the
  dimension of the browser window. They are
  available only after the page is loaded.
Netscape: window.innerHeight
             window.innerWidth
Properties of the screen object will capture the
  dimension of the user‟s monitor

                                              43
      Linear animation (diagonally across)
function moveText(){
  maxHeight = document.body.clientHeight –100;
  moverObject =document.getElementById(“mover”).style;
  moverObject.pixelLeft =moverObject.pixelLeft +2;
   moverObject.pixelTop =moverObject.pixelTop +2;
  if (moverObject.pixelLeft <= maxHeight){
       setTimeout(“moveText()”, 20);} }

<STYLE>
#mover {position:absolute;left:5px;top:5px;}
</STYLE>

<DIV ID=mover”> On the Road again </DIV>
                                                     44
Path animation
   You are not restricted to linear paths for
    animation. You can have the object
    move from point to point along a path
    that has any shape you want
   The x coordinate of each point in the
    path is stored into an array (x)
   The y coordinate of each point is stored
    into another array (y)

                                           45
Path animation (spiral in)
//store the consecutive increments in x and y (dx, and dy)
x= new Array(0,20,40,80, … -100,-50, …);
y= new Array(0,10,20,40, … -150, -80, …);
index=0;
function moveIt(objectID,dx,dy){
  moverObject =document.getElementById(objectID).style;
  moverObject.pixelLeft =moverObject.pixelLeft +dx;
   moverObject.pixelTop =moverObject.pixelTop +dy;}


Function spiral(){
 if (index <x.length-1){
      moveIt(“mover”,x[index],y[index]);
      index++;
      setTimeout(“spiral()”, 100);} }
End of Lecture




                 47

								
To top