SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
INLS 760 – Web Databases
  Lecture 9 – Javascript and DOM
                   Dr. Robert Capra
                     Spring 2009


                    Copyright 2007-2009, Robert G. Capra III       1




           What is Javascript?
• Client-side scripting language
  – Developed by Netscape
     https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference
     http://www.w3schools.com/JS/default.asp
     http://www.cs.brown.edu/courses/bridge/1998/res/javascript/java
       script-tutorial.html
  – Standardized by the European Computer
    Manufacturers Assoc. (ECMA)
  – Supported by all major web browsers
     • Differences among browsers
  – Has some similarity to Java, but not really
                                                                   2




                                                                       1
Simple Javascript Example
lect9/js-ex1.html
lect9/js ex1 html
<html>
<form>
   <input type="button" value="Hello world!“
       onclick="alert('Hello world!');">
</form>
</html>




                                                           3




           Javascript Example #2
<html>
<head>
    <script type="text/javascript">        lect9/js-ex2.html
        function hello(x)
             i
        {
          alert(x);
        }
    </script>
</head>
<body>
<form>
    <input type="button" value="Hello world!“
       onclick="hello('Hello world!');">
</form>
</body>
</html>
                                                           4




                                                               2
Document Object Model (DOM)
• Main ideas:
    – Give access to the structure of a web document
      through programming languages
       • Access on the client-side, so no additional server
         access needed
    – Treat the web document as an object




                                                              5




        DOM History/Evolution
•   W3C – http://www w3 org/DOM/
           http://www.w3.org/DOM/
•   Netscape
•   Microsoft IE
•   Levels 0, 1, 2, 3
    – http://xml coverpages org/dom html
      http://xml.coverpages.org/dom.html



                                                              6




                                                                  3
DOM Example                                HTML
<html>
<head>
<title>Chaucer DOM Example</title>                     HEAD              BODY
</head>
<body>
<h1>The Canterbury Tales</h1>
<h2>by Geoffrey Chaucer</h2>                   TITLE        H1       H2        TABLE
   <table border="1">
      <tr>
                                                       #text:       #text:
        <td>Whan that Aprill</td>
                                            #text:     The          By
        <td>with his shoures soote</td>
                                            Chaucer    Canterbury   Geoffrey
      </tr>                                 DOM        Tales        Chaucer
      <tr>                                  Example
        <td>The droghte of March</td>
        <td>hath perced to the roote</td>
                                     /                              TBODY
      </tr>
   </table>
<body>
                                                       TR           TR
</html>
                                                  TD   TD           TD         TD

                                                                                7




                     DOM Inspector
  • Firefox
       Tools       DOM Inspector
                          p



  To get the DOM Inspector:
       https://addons.mozilla.org/en-US/firefox/
          p                     g
       Search for "dom inspector"



                                                                                8




                                                                                       4
Related Javascript Objects
• Javascript has some built in bindings to objects
                      built-in
    –   window
    –   navigator
    –   screen
    –   history
    –   location


W3 Schools is a good resource:
http://www.w3schools.com/js/js_obj_htmldom.asp


                                                      9




         Javascript DOM bindings
• Javascript has built in bindings DOM
                 built-in
  objects
    – document
         • Is part of the window object
             – window.document



W3 Schools is a good resource:
  http://www.w3schools.com/js/js_obj_htmldom.asp


                                                     10




                                                          5
Using the Javascript Objects
<html>
<head>                                     lect9/js-ex3.html
                                           lect9/js-ex3 html
    <script type="text/javascript">
        function fred()
        {
            window.location = "http://sils.unc.edu/";
        }
    </script>
</head>
<body>
<form>
    <input type="button" value="Go to SILS" onclick="fred();">
</form>
</body>
</html>


                                                               11




       Accessing DOM Elements
• Using the document object + object names
<html>
<form name="fred">
   <input type="text" name="left">
   <input type="text" name="right">
   <input type="button" value="click me" onclick="hello();">
</form>
</html>



document.fred.left – refers to the i
d      t f d l ft      f        h input text box on the left
                                             b       h l f
document.fred.right – refers the input text box on the right




                                                               12




                                                                    6
Manipulating the current DOM
<html>
<head>
<script type="text/JavaScript">
   function h ll ()
   f    ti   hello()                        lect9/js-ex4.html
                                            lect9/js-ex4 html
   {
       document.fred.left.value = "hello";
       document.fred.right.value = "world";
   }
</script>
</head>
<form name="fred">
   <input type="text" name="left">
   <input type="text" name="right">
   <input type="button" value="click me" onclick="hello();">
</form>
</html>
            http://www.w3schools.com/htmldom/dom_obj_text.asp

                                                                13




            Javascript Calculator
• In class example
  In-class




                                                                14




                                                                     7
Accessing DOM Elements
• getElementById()
• getElementsByName()




                                                             15




  getElementById and getElementsByName

<html>
<head>                                      lect9/js-ex5.html
<script type="text/JavaScript">
   function h ll () {
   f    ti   hello()
       document.getElementById("left").value = "hello";
       document.getElementsByName("right")[0].value = "world";
   }
</script>
</head>
<form name="fred">
   <input type="text" value="" id="left">
   <input type="text" value="" name="right">
   <input type="button" value="click me" onclick="hello();">
</form>
</html>


      http://www.w3schools.com/HTMLDOM/dom_nodes_access.asp
                                                             16




                                                                  8
Writing to the DOM
<h2>Writing to the DOM example</h2>
Whan that Aprill with his shoures soote<br>               lect9/writetodom.html
The droghte of March hath perced to the roote,<br>
And bathed every veyne in swich licour<br>
Of which vertu engendred is the flour;<br>
<script language="JavaScript">
 script language JavaScript
   function ethel() {
      nrows = parseInt(document.form1.numrows.value);
      ncols = parseInt(document.form1.numcols.value);
      t = document.createElement("table");
                                                            Do example in
      for (i=0; i<nrows; i++) {
         r = document.createElement("tr");
                                                            DOM Inspector
         for (j=0; j<ncols; j++) {
            d = document.createElement("td");
            tx = document.createTextNode("r"+i+"c"+j);
            d.appendChild(tx);
            r.appendChild(d);
         }
         t.appendChild(r);
                d hild( )
      }
      document.body.appendChild(t);
      document.body.appendChild(document.createElement("br"));
   }
</script> <p>
<form name="form1">
   Num rows:<input type="text" name="numrows" size="3">
   Num cols:<input type="text" name="numcols" size="3">
   <input type="button" value="create table" onclick="ethel();">
</form>                                                                         17




                 Changing the DOM
<h1 id="fred">Title</h1>               lect9/changedom.html
<script>
   function foo(x)
   {
      document.getElementById("ethel").innerHTML = x;
      document.getElementById("fred").innerHTML = x;
   }
</script>
<div class="fred" id="ethel">Nothing yet</div>
<form>
   <input type="button" value="one"
   onclick= foo( one ) >
   onclick="foo('one')">
   <input type="button" value="two"         Do example in
   onclick="foo('two')">
</form>                                     DOM Inspector


                                                                                18




                                                                                     9
Row Highlighting
• Idea:
    – Highlight rows as user moves the mouse
    – Helps user see items in that row
• Real-world example:
    http://www.subway.com/applications/NutritionInfo/nutritionlist.aspx?id=sandwich
    http://www.subway.com/applications/NutritionInfo/scripts/nutritionlist.js

• Reference:
    http://www.w3schools.com/htmldom/dom_obj_style.asp




                                                                                      19




                   Row Highlighting
<h1>Table Highlighting</h1>

<script type="text/JavaScript">                     lect9/rowhighlighting.html
   function highlight(row)
   {                                                    Based on WS, Ch. 20, p. 286
      row.style.backgroundColor = "yellow";
       ow.sty e.bac g ou dCo o     ye ow ;
   }

   function unhighlight(row)
   {
                                                            QTP: How to do
   }
      row.style.backgroundColor = "";                       for columns?
</script>

<table border="1">
   <tr id="r1" onmouseover="highlight(r1)" onmouseout="unhighlight(r1)">
      <td>r1c1</td> <td>r1c2</td> <td>r1c3</td> <td>r1c4</td>
   </tr>
   <tr id " 2" onmouseover="highlight(r2)" onmouseout="unhighlight(r2)">
       id="r2"             "hi hli h ( 2)"            " hi hli h ( 2)"
      <td>r2c1</td> <td>r2c2</td> <td>r2c3</td> <td>r2c4</td>
   </tr>
   <tr id="r3" onmouseover="highlight(r3)" onmouseout="unhighlight(r3)">
      <td>r3c1</td> <td>r3c2</td> <td>r3c3</td> <td>r3c4</td>
   </tr>
   <tr id="r4" onmouseover="highlight(r4)" onmouseout="unhighlight(r4)">
      <td>r4c1</td> <td>r4c2</td> <td>r4c3</td> <td>r4c4</td>
   </tr>
</table>
                                                                                      20




                                                                                           10
Limiting Text Input
• Idea:
    – Limit the amount of text that can be entered
    – Show a count of the number of characters
• Real-world example:
    http://www.vtext.com

• Reference:
    Web Standards book, Chapter 23, Example 8, p. 341-342
                  book          23          8 p 341 342
    http://www.w3schools.com/htmldom/dom_obj_style.asp




                                                                           21




               Limiting Text Input
<h1>Text Input Counting</h1>                  lect9/textcount.html
<script type="text/JavaScript">                Based on WS, Ch. 23, p. 341-342
   function updatecount()
   {
      form1.fred.value = form1.ethel.value.length;
   }
</script>

<form name="form1" onkeyup="updatecount()">
   Characters entered:   <input name="fred" type="text" size="4"
   disabled="disabled">
   <br>
   <textarea name="ethel" cols="40" rows="3"></textarea>
</form>


                                          QTP: How do you stop
                                          input after 80 chars?

                                                                           22




                                                                                 11
Client-Side Form Validation
• Idea:
     – Catch input errors on forms before they are sent
       to the server
     – Save time and frustration
• Real-world example:
     Many sign-up forms

• Reference:
     Web Standards book, Chapter 23, Example 9 & 10, p. 343-351
     http://www.w3schools.com/htmldom/dom_obj_style.asp




                                                                               23




                     Form Validation
<h1>Form Validation</h1>
<script type="text/JavaScript">
   function validate_email()                       lect9/formvalidation.html
   {
      ev = document.form1.email.value;
      if (ev.indexOf('@') == -1) {
          document.getElementById("emailerror").className="ethel";
      } else {                                                         This example
          document.getElementById("emailerror").className="fred";
      }                                                                uses onblur
   }
</script>
<style>
.fred { visibility: hidden; }
.ethel { visibility: visible; color: red; }
</style>
<form name="form1">                                        In-class exercise:
   <table>
      <tr>                                                 add two password
          <td>Email address:</td>
          <td><input type="text" name="email" size="20"    fields d
                                                           fi ld and verify
                                                                          if
                onblur="validate_email();"></td>
          <td>                                             that the user inputs
             <div class="fred" id="emailerror">
                <-- there is a problem here, please fix    the same value for
             </div>
          </td>                                            each
      </tr>
   </table>
</form>
                                                                               24




                                                                                      12
document.getSelection()
<h2>document.getSelection() example</h2>         lect9/getselection.html

Whan that Aprill with his shoures soote
The droghte of March hath perced to the roote,
And bathed every veyne in swich licour
Of which vertu engendred is the flour;

<script language="JavaScript">
   function ethel() {
      var s = document.getSelection();
      document.form1.fred.value = s;
   }
</script>

<form name="form1">
   <input name="fred" type="text" value="foo">
   <input type="button" value="show selection" onclick="ethel();">
</form>




                                                                           25




                     Bookmarklets
• Idea:
    – Bookmark/Favorites can store JavaScript code
                                           p
• Real-world example:
    del.icio.us

• Reference:
    http://www.bookmarklets.com/

• Example:
    javascript:alert(document.getSelection());




                                                                           26




                                                                                13
Javascript and PHP
• PHP can output Javascript just as easily as
  html




                                                         27




  Lots of possibilities / examples
• JavaScript
• DOM
• Dynamic HTML
   – Drop down menus
   – Animation (use with restraint)
   – Moves away from web pages toward web applications


• http://www.w3schools.com/dhtml/dhtml_examples.asp


                                                         28




                                                              14
JavaScript Libraries
• YUI – Yahoo! User Interface Library
     – http://developer.yahoo.com/yui/
• script.aculo.us
     – http://script.aculo.us/
• jQuery
     – http://jquery.com/



                                                                                        29




                       YUI Drag and Drop
<!-- Based on YUI demo code -->
<!-- at http://developer.yahoo.com/yui/examples/dragdrop/dd-basic_clean.html -->
<script type="text/javascript"
  src="http://yui.yahooapis.com/2.5.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript"
    s c
    src="http://yui.yahooapis.com/2.5.0/build/dragdrop/dragdrop-min.js"></script>
           ttp://yu .ya ooap s.co / .5.0/bu d/d agd op/d agd op     .js   /sc pt
<style type="text/css">
.dd-demo     { position:relative; border:4px solid #666; text-align:center;
               color:#fff; cursor:move; height:60px; width:60px; }
.dd-demo-em { border:4px solid purple; }
#dd-demo-1 { background-color:#6D739A;top:0px; left:105px; }
#dd-demo-2 { background-color:#566F4E;top:50px; left:245px; }
#dd-demo-3 { background-color:#7E5B60;top:-150px; left:385px; }
</style>
<div id="dd-demo-1" class="dd-demo"></div>
<div id="dd-demo-2" class="dd-demo"></div>
<div id="dd-demo-3" class="dd-demo"></div>
<script type="text/javascript">
         var dd, dd2, dd3;
         YAHOO.util.Event.onDOMReady(function() {
                                                          lect9/yui-dragdrop.html
             dd = new YAHOO.util.DD("dd-demo-1");
             dd2 = new YAHOO.util.DD("dd-demo-2");
             dd3 = new YAHOO.util.DD("dd-demo-3");
         });
</script>

                                                                                        30




                                                                                             15
YUI Animation
<!-- Based on YUI demo code -->
<!-- at http://developer.yahoo.com/yui/examples/animation/motion_clean.html -->

<script src="http://yui.yahooapis.com/2.5.0/build/yahoo-dom-event/yahoo-dom-event.js">
    </script>
<script s c
 sc pt src="http://yui.yahooapis.com/2.5.0/build/animation/animation-min.js"></script>
              ttp://yu .ya ooap s.co / .5.0/bu d/a    at o /a   at o     .js   /sc pt

<style type="text/css">
#demo { background:#ccc; margin-bottom:1em; height:30px; width:30px; }
</style>

<div id="demo"></div>
<button id="demo-run">run</button>

<script type="text/javascript">
    var attributes = { points: { to: [600, 10] } };
    var anim = new YAHOO.util.Motion('demo', attributes);

    YAHOO.util.Event.on('demo-run', 'click', function() {
        anim.animate();
    });
</script>
                                                            lect9/yui-motion.html

                                                                                         31




                                                                                              16

Contenu connexe

Tendances

Basics of css and xhtml
Basics of css and xhtmlBasics of css and xhtml
Basics of css and xhtml
sagaroceanic11
 

Tendances (18)

Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
 
What is HTML 5?
What is HTML 5?What is HTML 5?
What is HTML 5?
 
Javascript 2009
Javascript 2009Javascript 2009
Javascript 2009
 
Rails Girls - Introduction to HTML & CSS
Rails Girls - Introduction to HTML & CSSRails Girls - Introduction to HTML & CSS
Rails Girls - Introduction to HTML & CSS
 
An Introduction to HTML5
An Introduction to HTML5An Introduction to HTML5
An Introduction to HTML5
 
JavaScript Basic
JavaScript BasicJavaScript Basic
JavaScript Basic
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Browser extension
Browser extensionBrowser extension
Browser extension
 
Xhtml 2010
Xhtml 2010Xhtml 2010
Xhtml 2010
 
The Future of the Web: HTML5
The Future of the Web: HTML5The Future of the Web: HTML5
The Future of the Web: HTML5
 
Introduccion a HTML5
Introduccion a HTML5Introduccion a HTML5
Introduccion a HTML5
 
Basics of css and xhtml
Basics of css and xhtmlBasics of css and xhtml
Basics of css and xhtml
 
Introduction to html 5
Introduction to html 5Introduction to html 5
Introduction to html 5
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
 
Introduction to WEB HTML, CSS
Introduction to WEB HTML, CSSIntroduction to WEB HTML, CSS
Introduction to WEB HTML, CSS
 
Web Projects: From Theory To Practice
Web Projects: From Theory To PracticeWeb Projects: From Theory To Practice
Web Projects: From Theory To Practice
 
Creating chrome-extension
Creating chrome-extensionCreating chrome-extension
Creating chrome-extension
 
Basics of node.js
Basics of node.jsBasics of node.js
Basics of node.js
 

Similaire à lect9

Document Object Model
Document Object ModelDocument Object Model
Document Object Model
chomas kandar
 

Similaire à lect9 (20)

Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
Html5 and web technology update
Html5 and web technology updateHtml5 and web technology update
Html5 and web technology update
 
Web designing workshop
Web designing workshopWeb designing workshop
Web designing workshop
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
 
html5
html5html5
html5
 
Web designing workshop
Web designing workshopWeb designing workshop
Web designing workshop
 
JavaScript and DOM
JavaScript and DOMJavaScript and DOM
JavaScript and DOM
 
Part 7
Part 7Part 7
Part 7
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Zotero Framework Translators
Zotero Framework TranslatorsZotero Framework Translators
Zotero Framework Translators
 
Intro to Web Standards
Intro to Web StandardsIntro to Web Standards
Intro to Web Standards
 
What you need to know bout html5
What you need to know bout html5What you need to know bout html5
What you need to know bout html5
 
JavaScripts & jQuery
JavaScripts & jQueryJavaScripts & jQuery
JavaScripts & jQuery
 

Plus de tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 

Plus de tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Dernier (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

lect9

  • 1. INLS 760 – Web Databases Lecture 9 – Javascript and DOM Dr. Robert Capra Spring 2009 Copyright 2007-2009, Robert G. Capra III 1 What is Javascript? • Client-side scripting language – Developed by Netscape https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference http://www.w3schools.com/JS/default.asp http://www.cs.brown.edu/courses/bridge/1998/res/javascript/java script-tutorial.html – Standardized by the European Computer Manufacturers Assoc. (ECMA) – Supported by all major web browsers • Differences among browsers – Has some similarity to Java, but not really 2 1
  • 2. Simple Javascript Example lect9/js-ex1.html lect9/js ex1 html <html> <form> <input type="button" value="Hello world!“ onclick="alert('Hello world!');"> </form> </html> 3 Javascript Example #2 <html> <head> <script type="text/javascript"> lect9/js-ex2.html function hello(x) i { alert(x); } </script> </head> <body> <form> <input type="button" value="Hello world!“ onclick="hello('Hello world!');"> </form> </body> </html> 4 2
  • 3. Document Object Model (DOM) • Main ideas: – Give access to the structure of a web document through programming languages • Access on the client-side, so no additional server access needed – Treat the web document as an object 5 DOM History/Evolution • W3C – http://www w3 org/DOM/ http://www.w3.org/DOM/ • Netscape • Microsoft IE • Levels 0, 1, 2, 3 – http://xml coverpages org/dom html http://xml.coverpages.org/dom.html 6 3
  • 4. DOM Example HTML <html> <head> <title>Chaucer DOM Example</title> HEAD BODY </head> <body> <h1>The Canterbury Tales</h1> <h2>by Geoffrey Chaucer</h2> TITLE H1 H2 TABLE <table border="1"> <tr> #text: #text: <td>Whan that Aprill</td> #text: The By <td>with his shoures soote</td> Chaucer Canterbury Geoffrey </tr> DOM Tales Chaucer <tr> Example <td>The droghte of March</td> <td>hath perced to the roote</td> / TBODY </tr> </table> <body> TR TR </html> TD TD TD TD 7 DOM Inspector • Firefox Tools DOM Inspector p To get the DOM Inspector: https://addons.mozilla.org/en-US/firefox/ p g Search for "dom inspector" 8 4
  • 5. Related Javascript Objects • Javascript has some built in bindings to objects built-in – window – navigator – screen – history – location W3 Schools is a good resource: http://www.w3schools.com/js/js_obj_htmldom.asp 9 Javascript DOM bindings • Javascript has built in bindings DOM built-in objects – document • Is part of the window object – window.document W3 Schools is a good resource: http://www.w3schools.com/js/js_obj_htmldom.asp 10 5
  • 6. Using the Javascript Objects <html> <head> lect9/js-ex3.html lect9/js-ex3 html <script type="text/javascript"> function fred() { window.location = "http://sils.unc.edu/"; } </script> </head> <body> <form> <input type="button" value="Go to SILS" onclick="fred();"> </form> </body> </html> 11 Accessing DOM Elements • Using the document object + object names <html> <form name="fred"> <input type="text" name="left"> <input type="text" name="right"> <input type="button" value="click me" onclick="hello();"> </form> </html> document.fred.left – refers to the i d t f d l ft f h input text box on the left b h l f document.fred.right – refers the input text box on the right 12 6
  • 7. Manipulating the current DOM <html> <head> <script type="text/JavaScript"> function h ll () f ti hello() lect9/js-ex4.html lect9/js-ex4 html { document.fred.left.value = "hello"; document.fred.right.value = "world"; } </script> </head> <form name="fred"> <input type="text" name="left"> <input type="text" name="right"> <input type="button" value="click me" onclick="hello();"> </form> </html> http://www.w3schools.com/htmldom/dom_obj_text.asp 13 Javascript Calculator • In class example In-class 14 7
  • 8. Accessing DOM Elements • getElementById() • getElementsByName() 15 getElementById and getElementsByName <html> <head> lect9/js-ex5.html <script type="text/JavaScript"> function h ll () { f ti hello() document.getElementById("left").value = "hello"; document.getElementsByName("right")[0].value = "world"; } </script> </head> <form name="fred"> <input type="text" value="" id="left"> <input type="text" value="" name="right"> <input type="button" value="click me" onclick="hello();"> </form> </html> http://www.w3schools.com/HTMLDOM/dom_nodes_access.asp 16 8
  • 9. Writing to the DOM <h2>Writing to the DOM example</h2> Whan that Aprill with his shoures soote<br> lect9/writetodom.html The droghte of March hath perced to the roote,<br> And bathed every veyne in swich licour<br> Of which vertu engendred is the flour;<br> <script language="JavaScript"> script language JavaScript function ethel() { nrows = parseInt(document.form1.numrows.value); ncols = parseInt(document.form1.numcols.value); t = document.createElement("table"); Do example in for (i=0; i<nrows; i++) { r = document.createElement("tr"); DOM Inspector for (j=0; j<ncols; j++) { d = document.createElement("td"); tx = document.createTextNode("r"+i+"c"+j); d.appendChild(tx); r.appendChild(d); } t.appendChild(r); d hild( ) } document.body.appendChild(t); document.body.appendChild(document.createElement("br")); } </script> <p> <form name="form1"> Num rows:<input type="text" name="numrows" size="3"> Num cols:<input type="text" name="numcols" size="3"> <input type="button" value="create table" onclick="ethel();"> </form> 17 Changing the DOM <h1 id="fred">Title</h1> lect9/changedom.html <script> function foo(x) { document.getElementById("ethel").innerHTML = x; document.getElementById("fred").innerHTML = x; } </script> <div class="fred" id="ethel">Nothing yet</div> <form> <input type="button" value="one" onclick= foo( one ) > onclick="foo('one')"> <input type="button" value="two" Do example in onclick="foo('two')"> </form> DOM Inspector 18 9
  • 10. Row Highlighting • Idea: – Highlight rows as user moves the mouse – Helps user see items in that row • Real-world example: http://www.subway.com/applications/NutritionInfo/nutritionlist.aspx?id=sandwich http://www.subway.com/applications/NutritionInfo/scripts/nutritionlist.js • Reference: http://www.w3schools.com/htmldom/dom_obj_style.asp 19 Row Highlighting <h1>Table Highlighting</h1> <script type="text/JavaScript"> lect9/rowhighlighting.html function highlight(row) { Based on WS, Ch. 20, p. 286 row.style.backgroundColor = "yellow"; ow.sty e.bac g ou dCo o ye ow ; } function unhighlight(row) { QTP: How to do } row.style.backgroundColor = ""; for columns? </script> <table border="1"> <tr id="r1" onmouseover="highlight(r1)" onmouseout="unhighlight(r1)"> <td>r1c1</td> <td>r1c2</td> <td>r1c3</td> <td>r1c4</td> </tr> <tr id " 2" onmouseover="highlight(r2)" onmouseout="unhighlight(r2)"> id="r2" "hi hli h ( 2)" " hi hli h ( 2)" <td>r2c1</td> <td>r2c2</td> <td>r2c3</td> <td>r2c4</td> </tr> <tr id="r3" onmouseover="highlight(r3)" onmouseout="unhighlight(r3)"> <td>r3c1</td> <td>r3c2</td> <td>r3c3</td> <td>r3c4</td> </tr> <tr id="r4" onmouseover="highlight(r4)" onmouseout="unhighlight(r4)"> <td>r4c1</td> <td>r4c2</td> <td>r4c3</td> <td>r4c4</td> </tr> </table> 20 10
  • 11. Limiting Text Input • Idea: – Limit the amount of text that can be entered – Show a count of the number of characters • Real-world example: http://www.vtext.com • Reference: Web Standards book, Chapter 23, Example 8, p. 341-342 book 23 8 p 341 342 http://www.w3schools.com/htmldom/dom_obj_style.asp 21 Limiting Text Input <h1>Text Input Counting</h1> lect9/textcount.html <script type="text/JavaScript"> Based on WS, Ch. 23, p. 341-342 function updatecount() { form1.fred.value = form1.ethel.value.length; } </script> <form name="form1" onkeyup="updatecount()"> Characters entered: <input name="fred" type="text" size="4" disabled="disabled"> <br> <textarea name="ethel" cols="40" rows="3"></textarea> </form> QTP: How do you stop input after 80 chars? 22 11
  • 12. Client-Side Form Validation • Idea: – Catch input errors on forms before they are sent to the server – Save time and frustration • Real-world example: Many sign-up forms • Reference: Web Standards book, Chapter 23, Example 9 & 10, p. 343-351 http://www.w3schools.com/htmldom/dom_obj_style.asp 23 Form Validation <h1>Form Validation</h1> <script type="text/JavaScript"> function validate_email() lect9/formvalidation.html { ev = document.form1.email.value; if (ev.indexOf('@') == -1) { document.getElementById("emailerror").className="ethel"; } else { This example document.getElementById("emailerror").className="fred"; } uses onblur } </script> <style> .fred { visibility: hidden; } .ethel { visibility: visible; color: red; } </style> <form name="form1"> In-class exercise: <table> <tr> add two password <td>Email address:</td> <td><input type="text" name="email" size="20" fields d fi ld and verify if onblur="validate_email();"></td> <td> that the user inputs <div class="fred" id="emailerror"> <-- there is a problem here, please fix the same value for </div> </td> each </tr> </table> </form> 24 12
  • 13. document.getSelection() <h2>document.getSelection() example</h2> lect9/getselection.html Whan that Aprill with his shoures soote The droghte of March hath perced to the roote, And bathed every veyne in swich licour Of which vertu engendred is the flour; <script language="JavaScript"> function ethel() { var s = document.getSelection(); document.form1.fred.value = s; } </script> <form name="form1"> <input name="fred" type="text" value="foo"> <input type="button" value="show selection" onclick="ethel();"> </form> 25 Bookmarklets • Idea: – Bookmark/Favorites can store JavaScript code p • Real-world example: del.icio.us • Reference: http://www.bookmarklets.com/ • Example: javascript:alert(document.getSelection()); 26 13
  • 14. Javascript and PHP • PHP can output Javascript just as easily as html 27 Lots of possibilities / examples • JavaScript • DOM • Dynamic HTML – Drop down menus – Animation (use with restraint) – Moves away from web pages toward web applications • http://www.w3schools.com/dhtml/dhtml_examples.asp 28 14
  • 15. JavaScript Libraries • YUI – Yahoo! User Interface Library – http://developer.yahoo.com/yui/ • script.aculo.us – http://script.aculo.us/ • jQuery – http://jquery.com/ 29 YUI Drag and Drop <!-- Based on YUI demo code --> <!-- at http://developer.yahoo.com/yui/examples/dragdrop/dd-basic_clean.html --> <script type="text/javascript" src="http://yui.yahooapis.com/2.5.0/build/yahoo-dom-event/yahoo-dom-event.js"></script> <script type="text/javascript" s c src="http://yui.yahooapis.com/2.5.0/build/dragdrop/dragdrop-min.js"></script> ttp://yu .ya ooap s.co / .5.0/bu d/d agd op/d agd op .js /sc pt <style type="text/css"> .dd-demo { position:relative; border:4px solid #666; text-align:center; color:#fff; cursor:move; height:60px; width:60px; } .dd-demo-em { border:4px solid purple; } #dd-demo-1 { background-color:#6D739A;top:0px; left:105px; } #dd-demo-2 { background-color:#566F4E;top:50px; left:245px; } #dd-demo-3 { background-color:#7E5B60;top:-150px; left:385px; } </style> <div id="dd-demo-1" class="dd-demo"></div> <div id="dd-demo-2" class="dd-demo"></div> <div id="dd-demo-3" class="dd-demo"></div> <script type="text/javascript"> var dd, dd2, dd3; YAHOO.util.Event.onDOMReady(function() { lect9/yui-dragdrop.html dd = new YAHOO.util.DD("dd-demo-1"); dd2 = new YAHOO.util.DD("dd-demo-2"); dd3 = new YAHOO.util.DD("dd-demo-3"); }); </script> 30 15
  • 16. YUI Animation <!-- Based on YUI demo code --> <!-- at http://developer.yahoo.com/yui/examples/animation/motion_clean.html --> <script src="http://yui.yahooapis.com/2.5.0/build/yahoo-dom-event/yahoo-dom-event.js"> </script> <script s c sc pt src="http://yui.yahooapis.com/2.5.0/build/animation/animation-min.js"></script> ttp://yu .ya ooap s.co / .5.0/bu d/a at o /a at o .js /sc pt <style type="text/css"> #demo { background:#ccc; margin-bottom:1em; height:30px; width:30px; } </style> <div id="demo"></div> <button id="demo-run">run</button> <script type="text/javascript"> var attributes = { points: { to: [600, 10] } }; var anim = new YAHOO.util.Motion('demo', attributes); YAHOO.util.Event.on('demo-run', 'click', function() { anim.animate(); }); </script> lect9/yui-motion.html 31 16