JavaScript DOM and CSS by nef90815


									     JavaScript DOM and CSS
• What we should learn in this lesson
  – What is DOM-The JavaScript Document Object
    Module, its architectures, methods ..
  – Dynamic Website structure: Placeholders and
    separated JavaScript files
  – Using DOM method to generate HTML
  – Formatting with CSS
   One JavaScript DOM exmple
• Why the following codes works?
  – <img src="http://.../~zhaoza/monkey.gif"
    document.the_image.src=‗ ~zhaoza/sun.gif ';
  – document.writeln(―<h1>test</h1>‖);
• DOM is the way JavaScript describes Web
  pages, and it lies at the heart of all
  JavaScript programming
    The JavaScript Document Object
• JavaScript is an Object-oriented programming language. The main
  idea of OOP is that information is organized in terms of objects.
  JavaScript is wonderful because it comes with a built-in library of
  objects. For example, a window is an object.
• Object properties
      Objects have properties that describe them. For example the windows
      object has properties such as its name, the words in its status bar, the
      URL of the document inside the window, and the window‘s document.
•   Objects methods
      In addition to properties, objects also have methods. Methods are the
      actions an object knows how to take. For example, Windows know how
      to open other Windows:"URL,""name,""features"). This
      tells JavaScript to use the open method of the Window object to open a
      new window. For the windows object, we already learn its methods such
      as: open(), alert(), prompt(), confirm() etc. Here introduces two more,
      focus and blur, The focus method moves a window that's behind other
      windows to the front. The blur method does the reverse — it moves a
      window behind other windows.
• One neat thing about objects is that the properties of an object can
  be objects too. For example, windows have a property called
  document that refers to the actual HTML document in the window.
  This document property is itself an object that has properties and
  methods of its own. We saw an example of this when we talked
  about image swapping. Go back to the last lesson, we learned that
  you can do an image swap like this:
  <a href="#" onMouseOver=
  That long string, window.document.the_image.src='button_d.gif',
  translates into: "Find the document property of the window, find
  the_image property of the document, find the src property of
  the_image, and set it to button_d.gif.―
• It may seem like a lot of detail to keep track of. The JavaScript
  Document Object Model describes a small hierarchy of objects.
  Here it is:
          JavaScript‘s objects
• The top box of the diagram represents your
  browser window. Following the line from that box
  down, you'll see it connects to seven more
  boxes. These are the properties of the browser
• The sixth box here, "document," represents the
  contents of your window. If you follow the little
  line leading out of the document box, you'll see it
  connects to six more boxes. These are the
  properties of the document object.
           Introduction to DOM
• The Document Object Model (DOM) is the model that
  describes how all elements in an HTML page, like input
  fields, images, paragraphs etc., are related to the
  topmost structure: the document itself. By calling the
  element by its proper DOM name, we can influence it.
• The purpose of the DOM:
   – It has been developed by the W3C to provide any programming
     language with access to each part of an XML document.
• What are the nodes of DOM
• How you can walk the DOM tree from node to node
• How to get a specific node and how to change its value
  or attributes.
• How to create nodes yourself, the ultimate purpose of
  the new DOM.
       What are the nodes of DOM
• In the Level 1 DOM, each object, whatever
  it may be exactly, is a Node. So if you do
      <P>This is a paragraph</P>
      you have created two nodes: an element P
      and a text node with content 'This is a
      The text node is inside the element, so it is
      considered a child node of the element.
      Conversely, the element is considered the
      parent node of the text node.
• If you do
      <P>This is a <B>paragraph</B></P>
      the element node P has two children, one of
      which has a child of its own:
• The element node P also has its own
  parent, this is usually the document,
  sometimes another element like a DIV. So
  the whole HTML document can be seen as
  a tree consisting of a lot of nodes, most of
  them having child nodes (and these, too,
  can have children).
DOM tree structure
Walking through the DOM tree
• Knowing the exact structure of the DOM tree, you can walk through it
  in search of the element you want to influence.
      For instance, assume the element node P has been stored in the variable
      x Then if we want to access the BODY we do
      We take the parent node of x and do something with it.
      To reach the B node:
      childNodes is an array that contains all children of the node x. Of course
      numbering starts at zero, so childNodes[0] is the text node 'This is a' and
      childNodes[1] is the element node B.
    – Two special cases: x.firstChild accesses the first child of x (the text node),
      while x.lastChild accesses the last child of x (the element node B).
• So supposing the P is the first child of the body, which in turn is the
  first child of the document, you can reach the element node B by either
  of these commands:
• document.firstChild.firstChild.lastChild;
• document.firstChild.childNodes[0].lastChild;
• document.firstChild.childNodes[0].childNodes[1];
  Dynamic Website structure: Placeholders
      and separated JavaScript files

   //W3C//DTD XHTML 1.1//EN"        // declaring new variables
   "   var date = new Date();
<html>                              var hour = date.getHours();
 <head>                             // demonstrating the if statement
  <title>AJAX Foundations:          if (hour >= 22 || hour <= 5)
   JavaScript and DOM</title>         document.write("Goodnight,
  <script type="text/javascript"        world!");
   src="jsdom.js"></script>         else
 </head>                              document.write("Hello, world!");
  I love you!
   Dynamic Website structure: Placeholders
       and separated JavaScript files
Morejsdom.html:                                  Morejsdos.js

<!DOCTYPE html PUBLIC "-//W3C//DTD               function process()
    XHTML 1.1//EN"                               {
    "         // Create the HTML code
<html>                                             var string;
 <head>                                            string = "<ul>"
  <title>AJAX Foundations: More JavaScript              + "<li>Black</li>"
    and DOM</title>                                     + "<li>Orange</li>"
  <script type="text/javascript"                        + "<li>Pink</li>"
    src="morejsdom.js"></script>                        + "</ul>";
 </head>                                           // obtain a reference to the <div> element on
 <body onload="process()">                             the page
  Hello Dude! Here's a cool list of colors for     myDiv =
    you:                                               document.getElementById("myDivEleme
  <br />                                               nt");
  <div id="myDivElement" />                        // add content to the <div> element
 </body>                                           myDiv.innerHTML = string;
</html>                                          }
 Dynamic Website structure: Placeholders
     and separated JavaScript files
• Access the named <div> element
  programmatically from the JavaScript function.
• Having the JavaScript code execute after the
  HTML template is loaded, so you can access the
  <div> element (no HTML elements are
  accessible from JavaScript code that executes
  referenced from the <head> element). You will
  do that by calling JavaScript code from the
  <body> element's onload event.
• Group the JavaScript code in a function for
  easier code handling.
        Using DOM method to generate
               HTML structures
                                                                           // create the second <ui> element and add a text node to it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"                          oLiOrange = document.createElement("li");
       "">                     oOrange = document.createTextNode("Orange");
<html>                                                                     oLiOrange.appendChild(oOrange);
  <title>AJAX Foundations: Even More JavaScript and DOM</title>            // create the third <ui> element and add a text node to it
  <script type="text/javascript" src="evenmorejsdom.js"></script>          oLiPink = document.createElement("li");
 </head>                                                                   oPink = document.createTextNode("Pink");
 <body onload="process()">
  <div id="myDivElement" />                                                // add the <ui> elements as children to the <ul> element
 </body>                                                                   oUl.appendChild(oLiBlack);
</html>                                                                    oUl.appendChild(oLiOrange);
                                                                           // obtain a reference to the <div> element on the page
function process()                                                         myDiv = document.getElementById("myDivElement");
  // create the first text node                                            // add content to the <div> element
  oHello = document.createTextNode                                         myDiv.appendChild(oHello);
              ("Hello Dude! Here's a cool list of colors for you:");       myDiv.appendChild(oUl);
 // create the <ul> element
 oUl = document.createElement("ul")

 // create the first <ui> element and add a text node to it
 oLiBlack = document.createElement("li");
 oBlack = document.createTextNode("Black");
                        Formatting with CSS
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">
  <title>AJAX Foundations: CSS</title>
  <script type="text/javascript" src="csstest.js"></script>
  <link href="styles.css" type="text/css" rel="stylesheet"/>

  <table id="table">
     <th id="tableHead">
       Product Name
     <td id="tableFirstLine">
     <td id="tableSecondLine">
       Big car
  <br />
  <input type="button" value="Set Style 1" onclick="setStyle1();" />
  <input type="button" value="Set Style 2" onclick="setStyle2();" />
                        Formatting with CSS
/ Change table style to style 1                                    .Table1
function setStyle1()                                               {
{                                                                    border: DarkGreen 1px solid;
  // obtain references to HTML elements                              background-color: LightGreen;
  oTable = document.getElementById("table");                       }
  oTableHead = document.getElementById("tableHead");               .TableHead1
  oTableFirstLine = document.getElementById("tableFirstLine");     {
  oTableSecondLine = document.getElementById("tableSecondLine");     font-family: Verdana, Arial;
  // set styles                                                      font-weight: bold;
  oTable.className = "Table1";
  oTableHead.className = "TableHead1";                               font-size: 10pt;
  oTableFirstLine.className = "TableContent1";                     }
  oTableSecondLine.className = "TableContent1";                    .TableContent1
}                                                                  {
                                                                     font-family: Verdana, Arial;
// Change table style to style 2                                     font-size: 10pt;
function setStyle2()                                               }
  // obtain references to HTML elements                            .Table2
  oTable = document.getElementById("table");                       {
  oTableHead = document.getElementById("tableHead");                 border: DarkBlue 1px solid;
  oTableFirstLine = document.getElementById("tableFirstLine");       background-color: LightBlue;
  oTableSecondLine = document.getElementById("tableSecondLine");   }
  // set styles                                                    .TableHead2
  oTable.className = "Table2";                                     {
  oTableHead.className = "TableHead2";                               font-family: Verdana, Arial;
  oTableFirstLine.className = "TableContent2";                       font-weight: bold;
  oTableSecondLine.className = "TableContent2";                      font-size: 10pt;
}                                                                  }
                                                                     font-family: Verdana, Arial;
                                                                     font-size: 10pt;
 Communicating between Windows
<html><head><title>Getting and using a window reference</title>
<script language="JavaScript">
<!-- hide me

// open a new window, In order to communicate with a window using
// JavaScript, you need a reference to that window.
var new_window ="hello.html","html_name","width=200,height=200");

//This opens a little window and assigns the variable new_window
//to refer to it. And then blur the new window

// show me -->
<h1>A new window has been opened and moved to the background.</h1>
<a href="#" onMouseOver="new_window.focus();">Bring it forward</a><br>
<a href="#" onMouseOver="new_window.blur();">Put it backward</a><br>

          Messing with the DOM in other
<head><title>Image Remote</title>

<script language="JavaScript">
<!-- hide me
//opens a new window and assigns the variable display_window to that window
var display_window ="slide_show_main.html","display_window");

// stop hiding -->
<a href="#" onClick="display_window.document.main_image.src= 'sky.jpg';return false;"> <img
<a href="#" onClick="display_window.document.main_image.src= 'sun.jpg';return false;"> <img
<a href="#" onClick="display_window.document.main_image.src= 'thau.jpg';return false;"> <img
<a href="#" onClick="display_window.document.main_image.src= 'monkey.jpg';return false;"><img

  Image Swapping

<div align="center">
<img src="sky.jpg"
  height="400" width="400">
                      Getting Framed
•   In JavaScript, Frames are treated just like windows
•   Main.html:
     <html><head><title>Using Frames with
     <frameset rows="25%,*">
     <frame src="frames_example_controls.html"
     <frame src="blank.html" name="target_frame">
•   Frames_example_controls.html:
     <html><head><title>Frames Example

     <a href="#"
        do!<br>');">Monkey see</a>

  Some other JavaScript Syntax
• Loops
    – While loops:
        while (some test is true) {
        do the stuff inside the curly braces
    – For loops:
          for (initial value; test; increment)
        { do this stuff; }
• Arrays- Arrays are lists.
    – An example to create an array of colors:
        var colors = new Array("red","blue","green");
          good thing about arrays is that elements of an array can be accessed by
          number. The first element is number 0 and can be accessed like this:
          var the_element = colors[0];
          After you execute this line of JavaScript, the variable the_element will hold
          the string "red."
              An example for Loops and
                 Arrays(slide show)
<html><head><title>URL Slideshow</title>

<script language = "JavaScript">
<!-- hide me

var url_names = new Array("","","");
var a_url;

for (loop = 0; loop < url_names.length; loop++)

    // make the name of a url, for example
    a_url = "http://www." + url_names[loop];

    // open a window
    var new_window=open(a_url,"new_window","width=300,height=300");

    // wait for the click
    alert("Hit OK for the next site");

// show me -->
<html> <head> <title>Function with No Parameters</title>
<script langauge="JavaScript">
<!-- hide me
       function announceTime() { //get the date, the hour, minutes, and seconds
                 var the_date = new Date();
                 var the_hour = the_date.getHours();
                 var the_minute = the_date.getMinutes();
                 var the_second = the_date.getSeconds();
                 //put together the string and alert with it
                 var the_time = the_hour + ":" + the_minute + ":" + the_second;
                 alert("The time is now: " + the_time); }
// show me -->
       <a href="#" onClick="announceTime(); return false;">

To top