+ All Categories
Home > Documents > Function: Javascript, Part 1 - Harvard...

Function: Javascript, Part 1 - Harvard...

Date post: 16-Apr-2018
Category:
Upload: vantruc
View: 237 times
Download: 2 times
Share this document with a friend
40
Table of Contents | All Slides | Link List | Examples | CSCI E-12 Function: Javascript, Part 1 March 11, 2009 Harvard University Division of Continuing Education Extension School Course Web Site: http://cscie12.dce.harvard.edu/ Copyright 1998-2009 David P. Heitmeyer Instructor email: [email protected] Course staff email: [email protected] Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html 1 of 40 3/11/2009 4:55 PM
Transcript

Table of Contents | All Slides | Link List | Examples | CSCI E-12

Function: Javascript, Part 1March 11, 2009

Harvard UniversityDivision of Continuing Education

Extension School

Course Web Site: http://cscie12.dce.harvard.edu/

Copyright 1998-2009 David P. Heitmeyer

Instructor email: [email protected] staff email: [email protected]

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

1 of 40 3/11/2009 4:55 PM

Client-side Web Parts: Markup, Style, Function

Markup (XHTML, HTML)StructureContent

Style (CSS)StylePresentationAppearance

Function (Javascript)ActionsManipulations

Structure + Style + Function: planets.html

Structure + Style: planets-style.html

Structure: planets-markup.html

JavaScript provides programmatic access to virtually all aspects of a page.

CSS propertiesMarkup contentForms, communication to Server

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

2 of 40 3/11/2009 4:55 PM

Javascript

JavaScript provides programmatic access to virtually all aspects of a page.

CSS propertiesMarkup contentForms, communication to Server

Wikipedia entries:

JavaScriptECMAScript

JavaScript is a scripting language most often used for client-side web development. It was the originating dialect of the ECMAScriptstandard. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript was influenced by many languagesand was designed to have a similar look to Java, but be easier for non-programmers to work with. The language is best known for its use inwebsites (as client-side JavaScript), but is also used to enable scripting access to objects embedded in other applications (for exampleMicrosoft Gadgets in Windows Vista Sidebar).

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

3 of 40 3/11/2009 4:55 PM

Javascript: Manipulate Styles

Manipulate Styles

Manipulate ContentCommunicate with Web Server (Ajax)

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

4 of 40 3/11/2009 4:55 PM

Javascript: Manipulate ContentManipulate Styles

Manipulate Content

Communicate with Web Server (Ajax)

US Senate

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

5 of 40 3/11/2009 4:55 PM

Javascript: Communicate with Web Server (Ajax)Manipulate StylesManipulate Content

Communicate with Web Server (Ajax)

Course Search

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

6 of 40 3/11/2009 4:55 PM

JavaScript and XHTML

Scripts in HTML Documents from the HTML 4 Specificationhttp://www.w3.org/TR/html4/interact/scripts.html<script> element

<!ELEMENT script - - %Script; -- script statements --><!ATTLIST script charset %Charset; #IMPLIED -- char encoding of linked resource -- type %ContentType; #REQUIRED -- content type of script language -- src %URI; #IMPLIED -- URI for an external script -- defer (defer) #IMPLIED -- UA may defer execution of script -- >

<script> element typically goes in head, but can be a child of body and many other elements.Note the <noscript> element for clients without JavaScript.

To function in all browsers, script element should not be empty, but should include a space, a comment, or even a simple returntrue; statement. Best:

<script src="jquery.js" type="text/javascript" > </script>

Don't use:

<script src="jquery.js" type="text/javascript" />

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

7 of 40 3/11/2009 4:55 PM

Event AttributesThese are attributes defined for X/HTML elements, which are "event attributes":

onclickonchangeonsubmitonloadonbluronfocusondblclickonkeydownonkeyuponkeypressonunloadonmousedownonmousemoveonmouseoutonmouseoveronmouseuponresetonselect

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

8 of 40 3/11/2009 4:55 PM

JavaScript in XHTML/HTMLExternal Script

<script src="/url/to/javascript/file.js" type="text/javascript" > </script> 1.

Script within XHTML document

<script type="text/javascript"> 1. /* 2. JavaScript code as content of script element 3. */ 4.</script> 5.

"Inline" scripts as values of event attributes

<a href="#" 1.

onclick="javascript:void(window.resizeTo(800,600))"> 2. Size Window to 800 x 600 3.

</a> 4.

These generally should be avoided, but are useful to create JavaScript-based bookmarks, known as favelets (Google Search:favelets).

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

9 of 40 3/11/2009 4:55 PM

Some Events

Example 6.1Example 6.1 Source:

view plain print ?

<ul> 1. <li><a href="#" onclick="setBackgroundColor('p1','#f33');" shape="rect" >Click to make "red"</a></li> 2. <li><a href="#" onclick="setBackgroundColor('p1','#33f');" shape="rect" >Click to make "blue"</a></li> 3. <li><a href="#" ondblclick="setBackgroundColor('p1','#3f3');" shape="rect" >Double Click to make "green"</a></li> 4. <li><a href="#" onmouseover="setBackgroundColor('p1','#ff3');" shape="rect" >Mouseover to make "yellow"</a></li> 5. <li><a href="#" onkeypress="setBackgroundColor('p1','#f3f');" shape="rect" >Keypress to make "magenta"</a></li> 6.</ul> 7.<p id="p1" >Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc lobortis orci a 8. odio. Donec cursus, felis eu pulvinar ornare, sem turpis dapibus elit, eget laoreet eros 9. quam vel dolor. Ut ante mauris, ullamcorper quis, posuere quis, lacinia a, felis. In 10. tincidunt malesuada pede. Donec varius lacus sed nisi. Donec rhoncus est ac erat. Duis 11. lobortis fringilla eros. Donec volutpat ligula eu neque. In hac habitasse platea 12. dictumst. Donec in massa. Aenean lectus ante, gravida et, luctus id, posuere at, pede. Nam 13. risus orci, rhoncus eu, aliquam ut, interdum ut, orci. Suspendisse rutrum, turpis sed 14. molestie gravida, libero risus iaculis ligula, quis tempor ligula enim vel sem. </p> 15.

In script element (within head element):

view plain print ?

function setBackgroundColor(myid,color) { 1. mynode = document.getElementById(myid); 2. mynode.style.backgroundColor = color; 3. return false; 4.} 5.

In style element (<style type="text/css">) within head element:

view plain print ?

* {font-family: Calibri,Tahoma,Verdana,Helvetica,sans-serif;} 1.#p1 { 2. padding: 1em; 3. border: medium solid black; 4. width: 75%; 5.} 6.

Example 6.1 Demonstrated

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

10 of 40 3/11/2009 4:55 PM

JS: Manipulate the PageJS can be used to manipulate CSS properties.

Note the use of event attributes (onclick, onmouseover, onmouseout) as well as a javascript: protocol in an href value.

Example 6.2Example 6.2 Source:

view plain print ?

<div id="cscie12-course" style="float: left; width: 50%; padding: 10px; margin: 10px; border: thin solid black;" > 1. <h3>Fundamentals of Website Development</h3> 2. <p> Harvard Extension School, Spring 2008-2009 3. <br/> CSCI E-12 4. <br/> Wednesday, 5:30 to 7:30 pm 5. <br/>Science Center Hall A 6. </p> 7. <p id="cscie12-description" >This course provides a comprehensive overview of website development. Students 8. explore the prevailing vocabulary, tools, and standards used in the field and learn 9. how the various facets—including XHTML, CSS, JavaScript, Ajax, multimedia, 10. scripting languages, HTTP, clients, servers, and databases—function together in 11. today's web environment. The course provides a solid web development foundation, 12. focusing on content and client-side (browser) components (XHTML, CSS, JavaScript, 13. multimedia), with an overview of the server-side technologies. In addition, 14. software and services that are easily incorporated into a website (for example, 15. maps, checkout, blogs, content management) are surveyed and discussed. Students 16. produce an interactive website on the topic of their choice for the final project and 17. leave the course prepared for more advanced and focused web development studies. 18. Prerequisites: CSCI E-1, or the equivalent experience.</p> 19.</div> 20.<div style="width: 20%; float: left; margin-left: 2em;" > 21. <p><strong>Align Description</strong></p> 22. <ul> 23. <li><a href="#" onclick="align('right')" shape="rect" >right</a></li> 24. <li><a href="#" onclick="align('left')" shape="rect" >left</a></li> 25. <li><a href="#" onclick="align('justify')" shape="rect" >justify</a></li> 26. </ul> 27. <p><strong>Hide/Show/Toggle Description</strong></p> 28. <ul> 29. <li><a href="javascript:hidedesc()" shape="rect" >Hide</a></li> 30. <li><a href="#" onclick="showdesc()" shape="rect" >Show</a></li> 31. <li><a href="#" onclick="toggledesc()" shape="rect" >Toggle</a></li> 32. </ul> 33. <p><strong>Set background-color</strong></p> 34. <ul> 35. <li><a href="#" onclick="backgroundcolor('#f33')" shape="rect" >red</a></li> 36. <li><a href="#" onclick="backgroundcolor('#3f3')" shape="rect" >green</a></li> 37. <li><a href="#" onclick="backgroundcolor('#ff3')" shape="rect" >yellow</a></li> 38. <li><a href="#" onclick="backgroundcolor('#33f')" shape="rect" >blue</a></li> 39. <li><a href="#" onmouseover="backgroundcolor('#f3f')" onmouseout="revertcolor()" shape="rect" >purple</a></li> 40. </ul> 41.</div> 42.

In example2.js

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

11 of 40 3/11/2009 4:55 PM

view plain print ?

function align(val) { 1. node = document.getElementById('cscie12-description'); 2. node.style.textAlign = val; 3. return false; 4.} 5.function hidedesc() { 6. node = document.getElementById('cscie12-description'); 7. node.style.display = 'none'; 8. return false; 9.} 10.function showdesc() { 11. node = document.getElementById('cscie12-description'); 12. node.style.display = 'block'; 13. return false; 14.} 15.function toggledesc() { 16. node = document.getElementById('cscie12-description'); 17. var currentdisplay = node.style.display; 18. if(currentdisplay == 'none') 19. showdesc(); 20. else 21. hidedesc(); 22.} 23.var previouscolor = '#fff'; 24.function backgroundcolor(color) { 25. node = document.getElementById('cscie12-course'); 26. previouscolor = node.style.backgroundColor; 27. node.style.backgroundColor = color; 28. return false; 29.} 30.function revertcolor() { 31. node = document.getElementById('cscie12-course'); 32. node.style.backgroundColor = previouscolor; 33. return false; 34.} 35.

In head element:

view plain print ?

<script src="example2.js" type="text/javascript"> </script> 1.

Example 6.2 Demonstrated

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

12 of 40 3/11/2009 4:55 PM

Exposing Additional Form ElementsAdditional relevant form elements are exposed based upon user input. Here, this is achieved by having the entire form in the markup, with acertain section hidden via CSS (display: none;). If "Yes" is chosen, the display property is changed to "block" through JS.

Example 6.3Example 6.3 Source:

view plain print ?

<form method="get" action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi" name="ice_cream" id="ice_cream" enctype="application/x-www-form-urlencoded" >

1.

<div> Would you like ice cream?<br/> 2. <input type="radio" name="want" id="ic_yes" value="yes" onclick="displayIceCreamOptions()" /> 3. <label for="ic_yes" >Yes</label><br/> 4. <input type="radio" name="want" id="ic_no" value="no" onclick="displayIceCreamOptions()" /> 5. <label for="ic_no" >No</label> </div> 6. 7. <div style="display: none; margin-left: 2em; background-color: #eee; padding: 1em; " id="icecream_options" > 8. <fieldset> 9. <legend>Ice Cream Options</legend> 10. <p>How would you like it?</p> 11. <input type="radio" id="container_cup" name="container" value="cup" /> 12. <label for="container_cup" >Cup</label> 13. <br/> 14. <input type="radio" id="container_cone" name="container" value="cone" /> 15. <label for="container_cone" >Cone</label> 16. <br/> 17. <p>Pick your toppings:</p> 18. <input type="checkbox" name="toppings" id="toppings_wc" value="whipcream" /> 19. <label for="toppings_wc" >Whipped cream</label> 20. <br/> 21. <input type="checkbox" name="toppings" id="toppings_j" value="jimmies" /> 22. <label for="toppings_j" >Jimmies</label> 23. <br/> 24. <input type="checkbox" name="toppings" id="toppings_nuts" value="nuts" /> 25. <label for="toppings_nuts" >Nuts</label> 26. <br/> 27. <input type="checkbox" name="toppings" id="toppings_cherry" value="cherry" /> 28. <label for="toppings_cherry" >Cheery</label> 29. </fieldset> 30. </div> 31. <p><input type="submit" /></p> 32.</form> 33.

In script element (within head element):

view plain print ?

function displayIceCreamOptions() { 1. var divico = document.getElementById('icecream_options'); 2. var state = divico.style.display; 3. if (document.forms['ice_cream'].want[0].checked) { 4. divico.style.display = 'block'; 5. } else { 6. divico.style.display = 'none'; 7. } 8.} 9.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

13 of 40 3/11/2009 4:55 PM

Example 6.3 Demonstrated

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

14 of 40 3/11/2009 4:55 PM

JS: Form ValidationValidate form input using the onsubmit event attribute.

Things to note:

onsubmit

false stops the form submissionthis is the magic objectValidate function accepts an argument, which is the form objectOn failure, focus is put on failed input and background color changed.

Example 6.4Example 6.4 Source:

view plain print ?

<form onsubmit="return Validate(this)" method="get" action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi" enctype="application/x-www-form-urlencoded" >

1.

<div> 2. <label for="YourName1" >Enter your name</label>: 3. <input type="text" id="YourName1" name="YourName" /> 4. <br/> 5. <input type="submit" value="Submit Information" /> 6.</div> 7.</form> 8.

In script element (within head element):

view plain print ?

function Validate(thisForm) { 1. if(thisForm.YourName.value == null || thisForm.YourName.value == "") { 2. alert("Please enter your name!"); 3. thisForm.YourName.focus(); 4. thisForm.YourName.style.backgroundColor = '#ff3'; 5. return false; 6. } else { 7. return true; 8. } 9.} 10.

Example 6.4 Demonstrated

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

15 of 40 3/11/2009 4:55 PM

Form Validation and Regular ExpressionsQ. What if we want to test for a string pattern other than "null" or "empty"?...A. Regular Expressions!

Regular Expression for an email address: (yes, this is simplified)/^[\w\._-]+@[\w\._-]+\.[a-zA-Z]{2,7}$/

^beginning of the string

[\w\._-]+[square brackets] indicate a character class"\w" is a word character"+" means 1 or more times

@the "@" part of the email address

\.[a-zA-Z]{2,7}matches the TLD (dot something, where something is 2 to 7 letters

$end of string

Example 6.5Example 6.5 Source:

view plain print ?

<form onsubmit="return Validate(this)" method="get" action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi" enctype="application/x-www-form-urlencoded" >

1.

<div> 2. <label for="email1" >Email Address</label>: 3. <input type="text" size="32" name="email" id="email1" /> 4. <br/> 5. <input type="submit" /> </div> 6.</form> 7.

In example5.js

view plain print ?

// validates that the entry is formatted as an email address 1.function Validate(thisForm) { 2. var tocheck = thisForm.email.value; 3. var re = /^[\w\._-]+@[\w\._-]+\.[a-zA-Z]{2,7}$/; 4. if (!tocheck.match(re)) { 5. alert("Please verify the email address format."); 6. thisForm.email.focus(); 7. thisForm.email.style.backgroundColor = '#ff9'; 8. return false; 9. } else { 10. return true; 11. } 12.} 13.

In head element:

view plain print ?

<script src="example5.js" type="text/javascript"> </script> 1.

Example 6.5 Demonstrated

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

16 of 40 3/11/2009 4:55 PM

Your Work Easier with JavaScript LibrariesjQueryPrototype / ScriptaculousYahoo! UIDojo

jQuery

Although all of the libraries above are very good and each have their particular strenghts, we'll focus primarily on jQuery. jQueryfunctionality is accessible regardless of background. Non-programmers can employ its straightforward selection and syntax, whiledevelopers can take advantage of its ease-of-use to develop and even extend jQuery.

jQuery comes with "core" functionality. Additional functionality can be added through a variety of core and contributed plugins.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

17 of 40 3/11/2009 4:55 PM

jQuery: Table StripingLet's get started with jQuery by "striping" a table. The plain table comes froma list of United States Senators.

Plain table:

Striped table:

Plain table: senate-plain.htmlStriped table: senate-striped.htmlInclude some Javascript libraries (jquery.js and write a function that selects the table rows and applies a class. Note that the jQueryselectors are like CSS selectors (and here we see custom jQuery selectors of :even and :odd).

<script type="text/javascript" src="../js/jquery-1.3.2.js"> </script> 1. <script type="text/javascript"> 2.$(document).ready(function() 3. { 4. $("#senatetable tbody tr:even").addClass('evenRow'); 5. $("#senatetable tbody tr:odd").addClass('oddRow'); 6. } 7.); </script> 8.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

18 of 40 3/11/2009 4:55 PM

Tables: Class gives Functionality

Query Tablesorter Plugin makes dealing with tables even easier!

Sortable table:

Tables are constructed with thead and tbody. Simply by giving them a class="sortable", the jQuery Tablesorter Plugin makes them'sortable' and 'striped':

Plain table: senate-plain.htmlSortable table: senate-sortable.html

JavascriptjQuery (jquery.js)jQuery Tablesorter Plugin (jquery.tablesorter.js)

CSSUse the "blue" theme from the tablsorter plugin

Assign tables with classesjQuery "ready" function

<?xml version="1.0" encoding="UTF-8"?> 1.<!DOCTYPE html 2. PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 3.<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> 4. <head> 5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 6. <title>United States Senate</title> 7. <link rel="stylesheet" type="text/css" 8. href="http://morpheus.dce.harvard.edu/jquery/tablesorter/themes/blue/style.css" /> 9. <script type="text/javascript" 10. src="http://morpheus.dce.harvard.edu/jquery/jquery-1.3.2.min.js"> </script><script type="text/javascript" src="http://morpheus.dce.harvard.edu/jquery/tablesorter/jquery.tablesorter.js"> </script>

11.

<script type="text/javascript"> 12.$(document).ready(function() 13. { 14. $("table.sortable").tablesorter({widgets: ['zebra']}); 15. } 16.); 17.</script></head> 18. <body> 19. <h1>United States Senate</h1> 20. <table id="senatetable" class="sortable tablesorter"> 21. <thead> 22. <tr> 23. <th>Name</th> 24. <th>State</th> 25. <th>Party</th> 26. <th>Birthday</th> 27. <th>Gender</th> 28. </tr> 29. </thead> 30. <tbody> 31. <tr>... 32.

Senate data used with permission from GovTrack.US.Table sorting is achieved through jQuery and the jQuery Tablesorter Plugin

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

19 of 40 3/11/2009 4:55 PM

Separation from MarkupIn an earlier example, we used the "onclick" attribute to specify a javascript function to call:

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

20 of 40 3/11/2009 4:55 PM

Separation from MarkupUse Javascript to add the "onclick" listener

Let's see how we can do this with jQuery. Items to note:

Separation. The "click" handler is bound via JavaScript and not the onclick attribute.Fancier. jQuery provides many "effects" and "animations" (basic ones here are fadeOut and fadeIn)Default Behavior Stopped. The default behavior for event propagation can be stopped.

Example 6.6Example 6.6 Source:

view plain print ?

<div id="cscie12-course2" style="float: left; width: 50%; padding: 10px; margin: 10px; border: thin solid black;" > 1. <h3>Fundamentals of Website Development</h3> 2. <p> Harvard Extension School, Spring 2008-2009 3. <br/> CSCI E-12 4. <br/> Wednesday, 5:30 to 7:30 pm 5. <br/>Science Center Hall A 6. </p> 7. <p id="cscie12-description2" >This course provides a comprehensive overview of website development. Students 8. explore the prevailing vocabulary, tools, and standards used in the field and learn 9. how the various facets—including XHTML, CSS, JavaScript, Ajax, multimedia, 10. scripting languages, HTTP, clients, servers, and databases—function together in 11. today's web environment. The course provides a solid web development foundation, 12. focusing on content and client-side (browser) components (XHTML, CSS, JavaScript, 13. multimedia), with an overview of the server-side technologies. In addition, 14. software and services that are easily incorporated into a website (for example, 15. maps, checkout, blogs, content management) are surveyed and discussed. Students 16. produce an interactive website on the topic of their choice for the final project and 17. leave the course prepared for more advanced and focused web development studies. 18. Prerequisites: CSCI E-1, or the equivalent experience.</p> 19.</div> 20.<div style="width: 20%; float: left; margin-left: 2em;" > 21. <p><strong>Hide/Show/Toggle Description</strong></p> 22. <ul> 23. <li><a href="#" id="hide" shape="rect" >Hide</a></li> 24. <li><a href="#" id="show" shape="rect" >Show</a></li> 25. <li><a href="#" id="toggle" shape="rect" >Toggle</a></li> 26. </ul> 27.</div> 28.

In script element (within head element):

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

21 of 40 3/11/2009 4:55 PM

view plain print ?

$(document).ready(function() { 1. $('a#hide').click(function(event){ 2. $('#cscie12-description2').fadeOut('slow'); 3. event.preventDefault(); 4. }); 5. $('a#show').click(function(event){ 6. $('#cscie12-description2').fadeIn('slow'); 7. event.preventDefault(); 8. }); 9. $('a#toggle').toggle( 10. function(event){ 11. $('#cscie12-description2').fadeOut('slow'); 12. event.preventDefault(); 13. }, 14. function(event){ 15. $('#cscie12-description2').fadeIn('slow'); 16. event.preventDefault(); 17. } 18. ); 19.}); 20.

Example 6.6 Demonstrated

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

22 of 40 3/11/2009 4:55 PM

Check and Uncheck All

Example: check_all.html

JavaScript:

Here we take advantage of an attribute value selector ([name=how]) the ability to retrieve and set attribute values, and also to completelyremove attributes. Note too that we iterate through each of the checkboxes.

$(document).ready(function() { 1. $('#checkall').click(function() { 2. $('[name=how]').attr('checked','checked'); 3. }); 4. $('#uncheckall').click(function() { 5. $('[name=how]').removeAttr('checked'); 6. }); 7. $('#toggle').click(function() { 8. $('[name=how]').each(function (i) { 9. if ($(this).attr('checked')) { 10. $(this).removeAttr('checked'); 11. } else { 12. $(this).attr('checked','checked'); 13. } 14. }); 15. }); 16. }); 17.

Markup:

<form action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi" method="get"> 1. <p>How did you hear about us?</p> 2. <p>[<a href="#" id="checkall">check all</a>] 3. [<a href="#" id="uncheckall">uncheck all</a>] 4. [<a href="#" id="toggle">toggle</a>] 5. </p> 6. <ul> 7. <li><input type="checkbox" name="how" value="radio"/>Radio</li> 8. <li><input type="checkbox" name="how" value="newspaper"/>Newspaper</li> 9. <li><input type="checkbox" name="how" value="magazine"/>Magazine</li> 10. <li><input type="checkbox" name="how" value="online"/>Online</li> 11. <li><input type="checkbox" name="how" value="friend"/>Friend</li> 12. </ul> 13. <input type="submit"/> 14.</form> 15.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

23 of 40 3/11/2009 4:55 PM

Duplicate Part of a Form

Example: add_another.html

JavaScript:

select the "div" we want to duplicateclone the "div" to create a new onechange the id (to maintain uniqueness) of the new divinsert the new div into the document

$(document).ready(function() { 1. var numberofphones = 1; 2. $('#addphone').click(function() { 3. numberofphones++; 4. newid = 'phone' + numberofphones; 5. var phonediv = $('#phone1'); 6. var newphonediv = phonediv.clone(); 7. newphonediv.attr('id',newid); 8. newphonediv.insertBefore('#addphone'); 9. }); 10. }); 11.

Markup:

<form action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi" method="get"> 1. <fieldset> 2. <legend>Contact Information</legend> 3. <div>Name: 4. <input type="text" name="name"/></div> 5. <div id="phone1">Phone: 6. <input type="text" name="phone"/> </div> 7. <input type="button" id="addphone" value="Add another phone"/> 8. </fieldset> 9. <div><input type="submit"/></div> 10.</form> 11.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

24 of 40 3/11/2009 4:55 PM

Chaining jQuerycalculate the new "id" stringselect the phone div to be duplicatedduplicate (clone) the phone divchange the id of the new phone divinsert the new phone div into the document

jQuery methods return nodes, so we can easily chain these steps together.

Stepwise:

$(document).ready(function() { 1. var numberofphones = 1; 2. $('#addphone').click(function() { 3. numberofphones++; 4. newid = 'phone' + numberofphones; 5. var phonediv = $('#phone1'); 6. var newphonediv = phonediv.clone(); 7. newphonediv.attr('id',newid); 8. newphonediv.insertBefore('#addphone'); 9. }); 10. }); 11.

Chained:

$(document).ready(function() { 1. var numberofphones = 1; 2. $('#addphone').click(function() { 3. numberofphones++; 4. newid = 'phone' + numberofphones; 5. $('#phone1').clone().attr('id',newid).insertBefore('#addphone'); 6. }); 7. }); 8.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

25 of 40 3/11/2009 4:55 PM

Unobtrusive Javascript

Principles of Unobtrusive JavaScript

SeparationGraceful degradationJS "best-practices"

Grace Degradation for "add another"

One strategy would be to hide the "Add Another" button and make it visible through JavaScript. We could go even further by creating the"Add Another" node in JS and then adding it to the page via JS.

$(document).ready(function() { 1. $('#addphone').css('display','inline'); 2. var numberofphones = 1; 3. $('#addphone').click(function() { 4. numberofphones++; 5. newid = 'phone' + numberofphones; 6. $('#phone1').clone().attr('id',newid).insertBefore('#addphone'); 7. }); 8. }); 9.

A browser with JS disabled would display form with a single phone field.

Example: add_another_unobtrusive.htmlWith JavaScript disabled in browser:

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

26 of 40 3/11/2009 4:55 PM

Tabs with jQuery

jQuery UI Tab Widget allows the easy creation of tabs from simple markup.

Example: tabs-jquery.html

With JS and CSS:

Without JS and CSS:

Markup:

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

27 of 40 3/11/2009 4:55 PM

<div id="tabs"> 1. <ul> 2. <li><a href="#basic">Overview</a> 3. </li> 4. 5. <li><a href="#description">Description</a> 6. </li> 7. <li><a href="#schedule">Schedule</a> 8. </li> 9. </ul> 10. 11. <div id="basic"> 12. <h2>Overview</h2> 13. 14. <h3>Fundamentals of Website Development 15. <br/>CSCI E-12</h3> 16. <p> 17. <br/> Wednesday, 5:30 to 7:30 pm 18. <br/>Science Center Hall A</p> 19. <p> Harvard Extension School, Spring 2008-09</p> 20. <p><a href="http://cscie12.dce.harvard.edu/">cscie12.dce.harvard.edu</a> 21. 22. </p> 23. </div> 24. 25. <div id="description"> 26. <h2>Course Description</h2> 27. <p>This course provides a comprehensive overview of website development. Students 28. explore the prevailing vocabulary, tools, and standards used in the field and learn 29. how the various facets—including XHTML, CSS, JavaScript, Ajax, multimedia, 30. scripting languages, HTTP, clients, servers, and databases—function together in 31. today's web environment. The course provides a solid web development foundation, 32. focusing on content and client-side (browser) components (XHTML, CSS, JavaScript, 33. multimedia), with an overview of the server-side technologies. In addition, 34. software and services that are easily incorporated into a website (for example, 35. maps, checkout, blogs, content management) are surveyed and discussed. Students 36. produce an interactive website on the topic of their choice for the final project and 37. leave the course prepared for more advanced and focused web development studies. 38. Prerequisites: CSCI E-1, or the equivalent experience. </p> 39. </div> 40. 41. <div id="schedule"> 42. <h2>Schedule of Lectures</h2> 43. 44. <ol> 45. <li>Introduction, Internet and Web Basics</li> 46. <li>Markup: XHTML and HTML, Part 1</li> 47. <li>Markup: XHTML and HTML, Part 2</li> 48. <li>Style: Cascading Style Sheets (CSS), Part 1</li> 49. <li>Style: Cascading Style Sheets (CSS), Part 2</li> 50. 51. <li>Style: CSS, Part 3, Accessibility, and Images</li> 52. <li>Function: Javascript, Part 1</li> 53. <li>Function: JavaScript and Ajax, Part 2</li> 54. <li>Function: External Functionality, Flash, Applets, and Web 2.0</li> 55. <li>Designing and Building a Site</li> 56. <li>Video and Multimedia on the Web</li> 57. 58. <li>Server-side: Dynamic content</li> 59. <li>Server-side: HTTP and Apache Web Server</li> 60. <li>Grab Bag</li> 61. </ol> 62. </div> 63.</div> 64.

JS and CSS:

<link rel="stylesheet" 1. href="http://morpheus.dce.harvard.edu/jquery/jquery-ui-1.7/css/smoothness/jquery-ui-1.7.custom.css" 2. type="text/css"/> 3.<script src="http://morpheus.dce.harvard.edu/jquery/jquery-1.3.2.min.js" 4. type="text/javascript"></script> 5.<script 6. src="http://morpheus.dce.harvard.edu/jquery/jquery-ui-1.7/js/jquery-ui-1.7.custom.min.js" 7. type="text/javascript"></script> 8.<script type="text/javascript"> 9. $(function(){ 10. $('#tabs').tabs(); 11. }); 12.</script> 13.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

28 of 40 3/11/2009 4:55 PM

Other jQuery UI WidgetsjQuery User Interface (UI)

jQuery UI provides abstractions for low-level interaction and animation, advanced effects and high-level, themeable widgets, built on top ofthe jQuery JavaScript Library, that you can use to build highly interactive web applications.

AccordionDatepickerDialogProgressbarSlidesTabs

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

29 of 40 3/11/2009 4:55 PM

jQuery Datepicker WidgetjQuery has plugins that will provide an unobtrusive "calendar" widget for picking dates.

Example: date_picker.html

Markup:

<form action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi"> 1. <p> 2. Enter a start date: <input class="date" type="text" size="32" name="startdate" id="startdate" /> 3. </p> 4. <p> 5. Enter an end date: <input class="date" type="text" size="32" name="enddate" id="enddate" /> 6. </p> 7. <input type="submit"/> 8.</form> 9.

CSS amd JS:

<link rel="stylesheet" 1. href="http://morpheus.dce.harvard.edu/jquery/jquery-ui-1.7/css/smoothness/jquery-ui-1.7.custom.css" 2. type="text/css"/> 3.<script src="http://morpheus.dce.harvard.edu/jquery/jquery-1.3.2.min.js" 4. type="text/javascript"></script> 5.<script 6. src="http://morpheus.dce.harvard.edu/jquery/jquery-ui-1.7/js/jquery-ui-1.7.custom.min.js" 7. type="text/javascript"></script> 8.<script type="text/javascript"> 9. $(document).ready(function(){ 10. $('input.date').datepicker(); 11. }) 12.</script> 13.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

30 of 40 3/11/2009 4:55 PM

jQuery Themes

Apply the "smoothness" theme (jquery-ui-1.7/css/smoothness/jquery-ui-1.7.custom.css):

Apply the "hot-sneaks" theme (jquery-ui-1.7/css/hot-sneaks/jquery-ui-1.7.custom.css):

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

31 of 40 3/11/2009 4:55 PM

Slideshow: ThickboxStructure + Style + Function: planets.html

Structure + Style: planets-style.html

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

32 of 40 3/11/2009 4:55 PM

Slideshow: Thickbox

Thickbox

ThickBox is a webpage UI dialog widget written in JavaScript on top of the jQuery library. Its function is to show a single image, multipleimages, inline content, iframed content, or content served through AJAX in a hybrid modal.

Example: Gallery with Thickbox

Add Thickbox JS, CSS, and give the "a" elemnts a class="gallery":

Gallery

Viewing an individual image:

A gallery with no JavaScript -- thumbnail images are linked to the full-sized image with a simple<a href="full/a.png"><img src="thumb/a.png"/></a>:

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

33 of 40 3/11/2009 4:55 PM

Example Galleries with Lightbox, Lightbox 2, and ThickboxView example galleries implemented in Lightbox and Lightbox 2 (using Prototype/Scriptaculous) as well as Thickbox (using jQuery).

Thickbox

Lightbox 2

Lightbox

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

34 of 40 3/11/2009 4:55 PM

Form ValidationjQuery Form Validation Plugin makes validating forms easy and flexible.

Form 1Use the jquery.validation.js plugin in a basic way.Validation rules are specified in "class" attributes

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

35 of 40 3/11/2009 4:55 PM

view plain print ?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 1.<html xmlns="http://www.w3.org/1999/xhtml"> 2.<head> 3. <title>A Form to Illustrate Validation using the jQuery Validation Plugin</title> 4. <link rel="stylesheet" type="text/css" href="form.css"/> 5. <script src="http://morpheus.dce.harvard.edu/jquery/jquery-1.3.2.js" 6. type="text/javascript"> </script> 7. <script type="text/javascript" 8. src="http://morpheus.dce.harvard.edu/jquery/validate/jquery.validate.js"> 9. </script> 10. <script type="text/javascript"> 11.$(document).ready(function(){ 12. $("#myForm").validate(); 13.}); 14.</script> 15.</head> 16.<body> 17. <form id="myForm" method="post" 18. action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi"> 19. <fieldset> 20. <legend>Information</legend> 21. <p> 22. <label for="name">Name</label> <em>(Required)</em> 23. <br/> 24. <input id="name" name="name" size="25" class="required"/> </p> 25. <p> 26. <label for="email">Email Address</label> <em>(Required)</em> 27. <br/> 28. <input id="email" name="email" size="25" class="required email"/> </p> 29. <p> 30. <label for="url">URL</label> <em>(Required)</em> 31. <br/> 32. <input id="url" name="url" size="25" class="required email"/> </p> 33. <p> 34. <input class="submit" type="submit" value="Submit Form"/> </p> 35. </fieldset> 36. </form> 37.</body> 38.</html> 39.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

36 of 40 3/11/2009 4:55 PM

Form ValidationRules are quite customizable and can be expressed in JavaScript sections and not in the code markup.

form2.html

view plain print ?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 1.<html xmlns="http://www.w3.org/1999/xhtml"> 2.<head> 3. <title>A Forum to Illustrate Validation using the jQuery Validation Plugin</title> 4. <link rel="stylesheet" type="text/css" href="form.css"/> 5. <script src="http://morpheus.dce.harvard.edu/jquery/jquery-1.3.2.js" 6. type="text/javascript"> </script> 7. <script type="text/javascript" 8. src="http://morpheus.dce.harvard.edu/jquery/validate/jquery.validate.js"> 9. </script> 10. <script type="text/javascript"> 11. $(document).ready(function(){ 12. var validation = $("#myForm").validate( 13. { 14. rules: { 15. name: { required: true, minlength: 2 }, 16. email: { required: true, email: true }, 17. url: { required: true, url: true } 18. } 19. }); 20. }); 21. </script> 22.</head> 23.<body> 24.<form id="myForm" method="post" action="http://morpheus.dce.harvard.edu/cgi-bin/echo.cgi"> 25.<fieldset> 26. <legend>A Form to Illustrate Validation using the jQuery Validation Plugin</legend> 27. <p> 28. <label for="name">Name</label><br/> 29. <input id="name" name="name" size="25"/> 30. </p> 31. <p> 32. <label for="email">Email Address</label><br/> 33. <input id="email" name="email" size="25"/> 34. </p> 35. <p> 36. <label for="url">URL</label><br/> 37. <input id="url" name="url" size="25" value="" /> 38. </p> 39. <p> 40. <input class="submit" type="submit" value="Submit"/> 41. </p> 42. </fieldset> 43. </form> 44.</body> 45.</html> 46.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

37 of 40 3/11/2009 4:55 PM

Form Validationform3.html

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

38 of 40 3/11/2009 4:55 PM

view plain print ?

$(document).ready(function(){ 1. var validation = $("#myForm").validate( 2. { 3. rules: { 4. name: { required: true, minlength: 2 }, 5. email: { required: true, email: true }, 6. url: { required: true, url: true }, 7. comments: { required: true }, 8. favnum: { required: true, number: true }, 9. favnum10: { required: true, number: true, min: 1, max: 10}, 10. color: {required: true}, 11. season: {required: true, minlength: 2}, 12. yourdate: { required: true, date: true } 13. }, 14. messages: { 15. season: { minlength: jQuery.format("Pick a minimum of {0} choices") } 16. }, 17. errorPlacement: function(error,element) { 18. if ( element.is("[name=color]") ) 19. error.appendTo( $('p#color') ); 20. else if ( element.is("[name=season]") ) 21. error.appendTo( $('p#season') ); 22. else 23. error.insertAfter(element); 24. } 25. }); 26.}); 27.

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

39 of 40 3/11/2009 4:55 PM

Example with YUIYahoo! User Interface Library (YUI)YUI Library Controls/Widgets

Tabs using YUI

Table of Contents | All Slides | Link List | Examples | CSCI E-12

Function: Javascript, Part 1 http://localhost:8080/cocoon/projects/cscie12/slides/20090311/handout.html

40 of 40 3/11/2009 4:55 PM


Recommended