Session 10 - JavaScript, Part 3

Harvard Extension School  
Spring 2021

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

Topics

  1. Javascript Resources
  2. JS Data Structures - array and "object" (key/value pair)
  3. Your work easier with jQuery
  4. Separation from Markup
  5. JavaScript - Minifying and CDNs
  6. jQuery Examples
  7. Add Another
  8. Unobtrusive Javascript, Progressive Enhancement, Graceful Degradation
  9. Pancake Menu
  10. Form Price Calculation
  11. jQuery UI
  12. Slideshow
  13. Form Validation with jQuery Validation Plugin
  14. Javascript Helping with Navigation

Session 10 - JavaScript, Part 3, slide1
Javascript Resources, slide2
Document Object Model (DOM), slide3
JS Data Structures - array and "object" (key/value pair), slide4
Your work easier with jQuery, slide5
jQuery and $(document).ready();, slide6
Separation from Markup, slide7
JavaScript - Minifying and CDNs, slide8
Load Your Core JS Library through a CDN, slide9
jQuery Examples, slide10
Ice Cream, slide11
Add Another, slide12
Chaining jQuery, slide13
Unobtrusive Javascript, Progressive Enhancement, Graceful Degradation, slide14
Progressive Enhancement for "add another", slide15
Ice Cream, slide16
Pancake Menu, slide17
Form Price Calculation, slide18
jQuery UI, slide19
Tabs with jQuery, slide20
jQuery UI Tabs, slide21
jQuery UI Tabs: Featured Content Slider, slide22
Rotating Carousels, slide23
Other jQuery UI Widgets, slide24
jQuery Datepicker Widget, slide25
jQuery UI Themes, slide26
Slideshow, slide27
Slideshow, slide28
Form Validation with jQuery Validation Plugin, slide29
Form Validation - setting rules with 'class' attributes, slide30
Form Validation - setting rules as configuration, slide31
Form Validation - setting custom messages and error placement, slide32
Form Validation - defining a custom rule, slide33
Javascript Helping with Navigation, slide34
Navigation , slide35
"You are here" with CSS, slide36
"You are here" with JavaScript, slide37
Clamshell Navigation, slide38

Presentation contains 38 slides

Javascript Resources

jQuery

jQuery is a JavaScript library that we will begin discussing next week!

Document Object Model (DOM)

web page
dom tree

<html>
         <head>
           <title>My Schools</title>
         </head>
         <body>
           <h1>My Schools</h1>
           <ul>
             <li>
               <a href="http://www.harvard.edu/">Harvard University</a><br/>
               <img src="images/veritas.gif" alt="Harvard Shield" height="84" width="72"/>
             </li>
             <li>
               <a href="http://www.ku.edu/">University of Kansas</a><br/>
               <img src="images/KUSeal.gif" alt="University of Kansas Seal" height="73" width="72"/>
             </li>
           </ul>
         </body>
       </html>

JS Data Structures - array and "object" (key/value pair)

JSON - JavaScript Object Notation

JSON array Example:


                       ['Autumn', 'Winter', 'Spring', 'Summer']
                     

JSON object Examples:

Simple "name/value" pairs:


                       {
                         "lastName" : "Bacow",
                         "firstName" : "Lawrence",
                         "email" : "president@harvard.edu"
                       }
                     

"name/value" pairs, with values being an array (list) of things:


                       {
                         "apples" : ['Macoun','Empire','Honey Crisp','Albemarle Pippin'],
                         "oranges" : ['Naval Orange','Tangelo','Clementine','Valencia Orange']
                       }
                     

More about JSON

A data format widely used in Ajax is JSON -- this format is used to pass data from the web server to the browser, and it is in a format that is easily worked with in JavaScript.

We first need to take a look at the JSON format and how we can work with it, and then we'll see how this works together in Ajax.

The introduction to JSON from json.org is a great place to start:

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

Your work easier with jQuery

What is jQuery?
jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

Easier:

jQuery Home

Learning jQuery

jQuery and $(document).ready();

$(document).ready(function(){})

See: $(document).ready() for more explanation, including the shorthand of $().

Separation from Markup

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

Example 10.1 - JS Separation from Markup - Example 10.1

 <div id="cscie12-course2" style="font-family: calibri,verdana,tahoma,helvetica,sans-serif; float: left; width: 50%; padding: 10px; margin: 10px; border: medium solid black; background-color: #ffb;">
   <h3>CSCI E-12: Fundamentals of Website Development   </h3>
   <p>Harvard Extension School
     <br/>
David Heitmeyer
     <br/>
CSCI E-12
   </p>
   <p id="cscie12-description2">This course provides a comprehensive overview of website development. Students explore the prevailing vocabulary, tools, and standards used in the field and learn how the various facets including HTML5, XHTML, CSS, JavaScript, Ajax, multimedia, scripting languages, HTTP, clients, servers, and databases function together in today's web environment. The course provides a solid web development foundation, focusing on content and client-side (browser) components (HTML5, XHTML, CSS, JavaScript, multimedia), with an overview of the server-side technologies. In addition, software and services that are easily incorporated into a website (for example, maps, checkout, blogs, content management) are surveyed and discussed. Students produce an interactive website on the topic of their choice for the final project and leave the course prepared for more advanced and focused web development studies.
   </p>
 </div>
 <div style="width: 20%; float: left; margin-left: 2em;">
   <p>
     <strong>Hide/Show/Toggle Description     </strong>
   </p>
   <ul>
     <li>
       <a href="#" id="hide">Hide       </a>
     </li>
     <li>
       <a href="#" id="show">Show       </a>
     </li>
     <li>
       <a href="#" id="toggle">Toggle       </a>
     </li>   </ul>
 </div>  

In script element within head element (<script>):

$(document).ready(function() {
  $('#hide').click(
   function(event){
     $('#cscie12-description2').fadeOut('slow');
     event.preventDefault();
   }
  );
  $('#show').click(
   function(event){
     $('#cscie12-description2').fadeIn('slow');
     event.preventDefault();
   }
  );
  $('#toggle').click(
   function(event) {
     console.log('toggle!');
     $('#cscie12-description2').toggle('slow');
     event.preventDefault();
   }
  );
});
 

jquery

JavaScript - Minifying and CDNs

Minified JS

What is "min" (minified) JS and CSS?

Comments and unnecessary whitespace are removed.

70% reduction!

Load Your Core JS Library through a CDN

MaxCDN (jQuery CDN), Google, Microsoft, and cdnjs.com host several JS libraries through their CDNs.
Using jQuery with a CDN

Three reasons why you should let Google host jQuery for you (or any other CDN):

CDN puts content closer to the user!

CDNs to Use

See: Using jQuery with a CDN

But not just jQuery! Several JavaScript libraries are hosted through various CDNs:

jQuery Examples

Ice Cream

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

Example 10.2 - Separation from Markup - Example 10.2 (Without Styles) | Example 10.2 JSFiddle

 <form method="get" name="ice_cream" id="ice_cream" action="https://cscie12.dce.harvard.edu/echo">
   <div>Would you like ice cream?
     <br/>

     <label>
       <input type="radio" name="want" id="ic_yes" value="yes"/>
Yes     </label>
     <label>
       <input type="radio" name="want" id="ic_no" value="no"/>
No     </label>
   </div>
   <fieldset id="icecream_options">
     <legend>Ice Cream Options     </legend>
     <p>How would you like it?
     </p>
     <label>
       <input type="radio" id="container_cup" name="container" value="cup"/>
Cup     </label>
     <br/>

     <label>
       <input type="radio" id="container_cone" name="container" value="cone"/>
Cone     </label>
     <br/>

     <p>Pick your toppings:
     </p>
     <label>
       <input type="checkbox" name="toppings" id="toppings_wc" value="whipcream"/>
Whipped cream     </label>
     <br/>

     <label>
       <input type="checkbox" name="toppings" id="toppings_j" value="jimmies"/>
Jimmies     </label>
     <br/>

     <label>
       <input type="checkbox" name="toppings" id="toppings_nuts" value="nuts"/>
Nuts     </label>
     <br/>

     <label>
       <input type="checkbox" name="toppings" id="toppings_cherry" value="cherry"/>
Cherry     </label>   </fieldset>
   <p>
     <input type="submit"/>

   </p>
 </form>   

In style element (<style>) within head element:

#icecream_options {
    background-color: #eee;
    margin-left: 2em;
}
label { display: block; }

In script element within head element (<script>):


$(document).ready(
  function(){
    $("#icecream_options").hide();
    $("input[name='want']").click(
      function(){
        displayIceCreamOptions();
      }
    );
  }
);

function displayIceCreamOptions() {
    if ($("input[name='want']:checked").val() == 'yes') {
      $('#icecream_options').fadeIn('slow');
    } else {
      $('#icecream_options').fadeOut('slow');
    }
}
 

ice cream options

ice cream options

ice cream options

Add Another

Example: add_another.html | Add Another in JSFiddle

add another

JavaScript:

$(document).ready(function() {
    var numberofphones = 1;
    $('#addphone').click(function() {
      numberofphones++;
      newid = 'phone' + numberofphones;
      var phonediv = $('#phone1');
      var newphonediv = phonediv.clone();
      newphonediv.attr('id',newid);
      newphonediv.insertBefore('#addphone');
  });
 });

Markup:

<form action="https://cscie12.dce.harvard.edu/echo" method="get">
  <fieldset>
    <legend>Contact Information</legend>
    <div>Name:
      <input type="text" name="name"/></div>
    <div id="phone1">Phone:
      <input type="text" name="phone"/> </div>
      <input type="button" id="addphone" value="Add another phone"/>
  </fieldset>
  <div><input type="submit"/></div>
</form>

Chaining jQuery

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

Stepwise:

$(document).ready(function() {
    var numberofphones = 1;
    $('#addphone').click(function() {
      numberofphones++;
      newid = 'phone' + numberofphones;
      var phonediv = $('#phone1');
      var newphonediv = phonediv.clone();
      newphonediv.attr('id',newid);
      newphonediv.insertBefore('#addphone');
  });
 });

Chained: (select → clone → change attribute → insert into DOM)

$(document).ready(function() {
    var numberofphones = 1;
    $('#addphone').click(function() {
      numberofphones++;
      newid = 'phone' + numberofphones;
      $('#phone1').clone().attr('id',newid).insertBefore('#addphone');
  });
 });

Unobtrusive Javascript, Progressive Enhancement, Graceful Degradation

Principles of Unobtrusive JavaScript

Progressive Enhancement for "add another"

$(document).ready(function() {
  $('#addphone').css('display','inline');
  var numberofphones = 1;
  $('#addphone').click(function() {
      numberofphones++;
      newid = 'phone' + numberofphones;
      $('#phone1').clone().attr('id',newid).insertBefore('#addphone');
  });
 });

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

Example: add_another_unobtrusive.html
With JavaScript disabled in browser:
add another

Ice Cream

Start with everything visible, then hide with JavaScript:
Key piece here is: $("#icecream_options").hide();

Example 10.3 - Separation from Markup - Example 10.3 (Without Styles)

 <form method="get" name="ice_cream" id="ice_cream" action="https://cscie12.dce.harvard.edu/echo">
   <div>Would you like ice cream?
     <br/>

     <label>
       <input type="radio" name="want" id="ic_yes" value="yes"/>
Yes     </label>
     <label>
       <input type="radio" name="want" id="ic_no" value="no"/>
No     </label>
   </div>
   <fieldset id="icecream_options">
     <legend>Ice Cream Options     </legend>
     <p>How would you like it?
     </p>
     <label>
       <input type="radio" id="container_cup" name="container" value="cup"/>
Cup     </label>
     <label>
       <input type="radio" id="container_cone" name="container" value="cone"/>
Cone     </label>
     <p>Pick your toppings:
     </p>
     <label>
       <input type="checkbox" name="toppings" id="toppings_wc" value="whipcream"/>
Whipped cream     </label>
     <label>
       <input type="checkbox" name="toppings" id="toppings_j" value="jimmies"/>
Jimmies     </label>
     <label>
       <input type="checkbox" name="toppings" id="toppings_nuts" value="nuts"/>
Nuts     </label>
     <label>
       <input type="checkbox" name="toppings" id="toppings_cherry" value="cherry"/>
Cherry     </label>   </fieldset>
   <p>
     <input type="submit"/>

   </p>
 </form>   

In style element (<style>) within head element:

#icecream_options {
    background-color: #eee;
    margin-left: 2em;
}
label { display: block; }

In script element within head element (<script>):

$(document).ready(function(){
    $("#icecream_options").hide();
    $("input[name='want']").click(function(){
      displayIceCreamOptions();
    });
});
function displayIceCreamOptions() {
    if ($("input[name='want']:checked").val() == 'yes') {
      $('#icecream_options').fadeIn('slow');
    } else {
      $('#icecream_options').fadeOut('slow');
    }
}
 

ice cream options

ice cream options

Pancake Menu

Mobile Pancake/Hamburger Menus

pancake menu

pancake menu

Form Price Calculation

Let's revisit the Dado Lunch Form, this time calculating a price!

lunch menu

jQuery UI

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.

jquery ui

Tabs with jQuery

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

With JS and CSS:
tabs

Without JS and CSS:
tabs

Markup:

<div id="tabs">
    <ul>
      <li><a href="#basic">Overview</a>
      </li>

      <li><a href="#description">Description</a>
      </li>
      <li><a href="#schedule">Schedule</a>
      </li>
    </ul>

    <div id="basic">
      <h2>Overview</h2>
      <h3>Fundamentals of Website Development
        <br/>CSCI E-12</h3>
      <p>Harvard Extension School</p>
      <p><a href="http://cscie12.dce.harvard.edu/">cscie12.dce.harvard.edu</a>
        </p>
        <p><strong>Format: Online (live or on demand) web conference</p>
        <p><strong>Time: </strong>Tuesdays, 8:10-10:10 pm, or on demand</p>
    </div>

    <div id="description">
      <h2>Course Description</h2>
      <p>This course provides a comprehensive overview of website development. Students explore the prevailing vocabulary, tools, and standards used in the field and learn how the various facets—including HTML5, CSS, JavaScript, Ajax, multimedia, scripting languages, HTTP, clients, servers, and databases—function together in today's web environment. The course provides a solid web development foundation, focusing on content and client-side (browser) components (HTML5, CSS, JavaScript, multimedia), with an overview of the server-side technologies. In addition, software and services that are easily incorporated into a website (for example, maps, checkout, blogs, content management) are surveyed and discussed. Students produce an interactive website on the topic of their choice for the final project and leave the course prepared for more advanced and focused web development studies.</div>

    <div id="schedule">
      <h2>Schedule of Lectures</h2>

      <ol>
        <li>Getting Started - Internet, WWW, HTML</li>
        <li>Markup (HTML)</li>
        <li>Markup (HTML) and Style (CSS)</li>
        <li>Style (CSS), Part 2 - Block Model, Colors, Images, Lists</li>
        <li>Style (CSS), Part 3 - CSS and Layouts</li>
        <li>Style (CSS), Part 4 - Techniques and CSS Frameworks</li>
        <li>JavaScript, Part 1 - JS Introduction</li>
        <li>JavaScript, Part 2 - JS and jQuery</li>
        <li>JavaScript, Part 3 - Integrating JS Functionality</li>
        <li>JavaScript, Part 4 - XHR and dynamic pages</li>
        <li>Web Content Management Systems</li>
        <li>Server-Side, Part 1 - Dynamic Content</li>
        <li>Server-Side, Part 2 - HTTP, Web Server Configuration</li>
        <li>Grab Bag of Topics</li>
        <li>Final Project Due and In-Class Presentations (Optional)</li>
</ol>
    </div>
  </div>

JS and CSS:

<link rel="stylesheet"
  href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/sunny/jquery-ui.css"
   media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"> </script>
<script>
  $(document).ready(
    function(){
      $('#tabs').tabs();
    }
  );
</script>

jQuery UI Tabs

If you use UI tabs, use for content, NOT for site navigation!

Wrong Way

jQuery UI Tabs: Featured Content Slider

Featured content slider using jQuery UI

featured content hot dogs

Javascript: (just like any other jQuery UI Tabs:

$(document).ready(function(){
     $("#featured").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, true);
});

Markup:

<div id="featured" >
  <div id="fragment-1"> <img src="images/featured1.jpg"  />
    <div class="info" >...</div>
  </div>
  <div id="fragment-2"> <img src="images/featured2.jpg"  />
    <div class="info" >...</div>
  </div>
  <div id="fragment-3"> <img src="images/featured3.jpg"  />
    <div class="info" >...</div>
  </div>
  <!-- ... -->
  <div id="fragment-7"> <img src="images/featured7.jpg"  />
    <div class="info" >...</div>
  </div>
  <ul class="ui-tabs-nav">
    <li id="nav-fragment-1"><a href="#fragment-1"><img src="thumbnail1.jpg"/></a></li>
    <li id="nav-fragment-2"><a href="#fragment-2"><img src="thumbnail2.jpg"/></a></li>
    <li id="nav-fragment-3"><a href="#fragment-3"><img src="thumbnail3.jpg"/></a></li>
    <!-- ... -->
    <li id="nav-fragment-7"><a href="#fragment-3"><img src="thumbnail7.jpg"/></a></li>
  </ul>
</div>

Rotating Carousels

Harvard - Carousel to No Carousel

Carousel:
harvard carousel

No Carousel:
harvard no carousel

Other jQuery UI Widgets

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library. Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is the perfect choice.

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

jQuery Datepicker Widget

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

Example: date_picker.html

Markup:

<form action="https://cscie12.dce.harvard.edu/echo">
  <p>
    Enter a start date: <input class="date" type="text" size="32" name="startdate" id="startdate" />
  </p>
  <p>
    Enter an end date: <input class="date" type="text" size="32" name="enddate" id="enddate" />
  </p>
  <input type="submit"/>
</form>

CSS amd JS:

<link rel="stylesheet"
  href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"
   media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"
    ></script>
<script
    src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"
    ></script>
<script >
  $(document).ready(function(){
    $('input.date').datepicker();
  })
</script>

jQuery UI Themes

Apply the "smoothness" theme
(themes/smoothness/jquery-ui.css):
datepicker

Apply the "hot-sneaks" theme
(themes/hot-sneaks/jquery-ui.css):
datepicker

Slideshow

Structure + Style + Function: solarsystem.html
markup

Structure + Style: solarsystem-style.html
markup

Slideshow

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

Example Galleries

View example galleries implemented in various "lightbox" or "slideshow" programs.

slideshow

slideshow

Form Validation with jQuery Validation Plugin

jQuery Validation Plugin makes validating forms easy and flexible.

You can use it "out of the box" quickly and create validation rules by simply using class names in your input elements. You can use this validation plugin in more sophisticated ways as well, including providing your own validation methods.

jQuery Validation Plugin Home Page

Form Validation - setting rules with 'class' attributes

jQuery Validation Plugin makes validating forms easy and flexible.

form

<html>
<head>
  <title>A Form to Illustrate Validation using the jQuery Validation Plugin</title>
  <link rel="stylesheet"  href="form.css"/>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<script
    src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js">
</script>
<script >
$(document).ready(function(){
    $("#myForm").validate();
});
</script>
</head>
<body>
  <form  id="myForm" method="post"
    action="https://cscie12.dce.harvard.edu/echo">
    <fieldset>
      <legend>Information</legend>
      <p>
        <label for="name">Name</label> <em>(Required)</em>
        <br/>
        <input id="name" name="name" size="25" class="required"/> </p>
      <p>
        <label for="email">Email Address</label> <em>(Required)</em>
        <br/>
        <input id="email" name="email" size="25" class="required email"/> </p>
      <p>
        <label for="url">URL</label> <em>(Required)</em>
        <br/>
        <input id="url" name="url" size="25" class="required url"/> </p>
      <p>
        <input class="submit" type="submit" value="Submit Form"/> </p>
    </fieldset>
  </form>
</body>
</html>

Form Validation - setting rules as configuration

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

form validation

<html>
<head>
  <title>A Form to Illustrate Validation using the jQuery Validation Plugin</title>
  <link rel="stylesheet"  href="form.css"/>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<script
    src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js">
</script>
<script >
$(document).ready(function(){
  var validation = $("#myForm").validate(
    {
    rules: {
      name:  { required: true, minlength: 2 },
      email: { required: true, email: true },
      url:   { required: true, url: true }
    }
  });
});
</script>
</head>
<body>
<form id="myForm" method="post" action="https://cscie12.dce.harvard.edu/echo">
<fieldset>
   <legend>A Form to Illustrate Validation using the jQuery Validation Plugin</legend>
   <p>
     <label for="name">Name</label>
     <input id="name" name="name" size="25"/>
   </p>
   <p>
     <label for="email">Email Address</label>
     <input id="email" name="email" size="25"/>
   </p>
   <p>
     <label for="url">URL</label>
     <input id="url" name="url" size="25"  value="" />
   </p>
 <p>
     <input class="submit" type="submit" value="Submit"/>
   </p>
 </fieldset>
 </form>
</body>
</html>

Form Validation - setting custom messages and error placement

form validation

  $(document).ready(function(){
    var validation = $("#myForm").validate(
     {
       rules: {
         name: { required: true, minlength: 2 },
         email: { required: true, email: true },
         url: { required: true, url: true },
         favnum: { required: true, number: true },
         favnum10: { required: true, number: true, min: 1, max: 10},
         color: {required: true},
         season: {required: true, minlength: 2},
         yourdate: { required: true, date: true }
       },
       messages: {
              season: { minlength: jQuery.validator.format("Pick a minimum of {0} choices") }
       },
       errorPlacement: function(error,element) {
           if ( element.is("[name=color]") )
              error.appendTo( $('p#color') );
           else if ( element.is("[name=season]") )
              error.appendTo( $('p#season') );
           else if ( element.is("[name=comments]") )
              error.insertAfter( $('label[for=comments]') );
           else
              error.insertAfter(element);
       }
     });
  });

Form Validation - defining a custom rule

Here we define a new validation rule called "netid" (three characters and three numbers, e.g. 'abc123')

      $(document).ready( function() {
      /* addMethod for netid validation */
      $.validator.addMethod(
        "netid",
         function(value, element) {
            var pattern = /^[a-zA-Z]{3}[0-9]{3}$/;
            return this.optional( element ) || pattern.test( value );
         },
         'Please enter a valid NetID (e.g. abc123).'
       );
    var validation = $("#myForm").validate(
     {
       rules: {
         name: { required: true, minlength: 2 },
         email: { required: true, email: true },
         netid: { required: true, netid: true }
       }
     });
  });

Javascript Helping with Navigation

navigation

Navigation

Iroquois Constitution

<html>
  <head>
    <title>The Great Binding Law, Gayanashagowa (Constitution of the Iroquois Nations)</title>
    <link rel="stylesheet"  href="style.css" />
  </head>
  <body id="part1">
    <?php include("inc/header.php"); ?>
    <?php include("inc/nav.php"); ?>
    <main>
      <?php include("inc/content1.php"); ?>
    </main>
    <?php include("inc/footer.php"); ?>
  </body>
</html>

"You are here" with CSS

"You are Here" CSS Example in JSFiddle

you are here

<nav id="navigation">
  <ul id="mainnav">
    <li id="navpart1"><a href="1.shtml">The Great Binding Law, Gayanashagowa</a></li>
    <li id="navpart2"><a href="2.shtml">Rights, Duties and Qualifications of Lords</a></li>
    <li id="iamhere"><a href="3.shtml">Election of Pine Tree Chiefs</a></li>
    <li id="navpart4"><a href="4.shtml">Names, Duties and Rights of War Chiefs</a></li>
    <li id="navpart5"><a href="5.shtml">Clans and Consanguinity</a></li>
    <li id="navpart6"><a href="6.shtml">Official Symbolism</a></li>
    <li id="navpart7"><a href="7.shtml">Laws of Adoption</a></li>
    <li id="navpart8"><a href="8.shtml">Laws of Emigration</a></li>
    <li id="navpart9"><a href="9.shtml">Rights of Foreign Nations</a></li>
    <li id="navpart10"><a href="10.shtml">Rights and Powers of War</a></li>
    <li id="navpart11"><a href="11.shtml">Treason or Secession of a Nation</a></li>
    <li id="navpart12"><a href="12.shtml">Rights of the People of the Five Nations</a></li>
    <li id="navpart13"><a href="13.shtml">Religious Ceremonies Protected</a></li>
    <li id="navpart14"><a href="14.shtml">The Installation Song</a></li>
    <li id="navpart15"><a href="15.shtml">Protection of the House</a></li>
    <li id="navpart16"><a href="16.shtml">Funeral Addresses</a></li>
  </ul>
</nav>

And the CSS:

#navigation a {
  /* Rules for navigation items */
}
#navigation a:hover {
  /* Rules for navigation items */
}

/* Rules specific for "you are here" */
#navigation #iamhere a,
#navigation #iamhere a:hover {
  /* Rules for the "you are here" item */
}

"You are here" with JavaScript

View this technique in action.Example in JSFiddle

  1. Each body is uniquely identified (id)
  2. Each navigation list item gets an id
  3. CSS rule for id="iamhere"
  4. JavaScript to set the "iamhere" id

Note the id of the body:

<html>
<head>
    <title>Election of Pine Tree Chiefs (Constitution of the Iroquois Nations)</title>
    <link rel="stylesheet"  href="style.css" />
  </head>
  <body id="part3">
    <?php include("inc/header.php"); ?>
    <?php include("inc/nav.php"); ?>
    <main>
      <?php include("inc/content3.php"); ?>
    <main>
    <?php include("inc/footer.php"); ?>
  </body>
</html>

Each navigation item has an id:

<nav id="navigation">
<ul id="mainnav">
<li id="navpart1"><a href="1.shtml">The Great Binding Law, Gayanashagowa</a></li>
<li id="navpart2"><a href="2.shtml">Rights, Duties and Qualifications of Lords</a></li>
<li id="navpart3"><a href="3.shtml">Election of Pine Tree Chiefs</a></li>
<li id="navpart4"><a href="4.shtml">Names, Duties and Rights of War Chiefs</a></li>
<li id="navpart5"><a href="5.shtml">Clans and Consanguinity</a></li>
<li id="navpart6"><a href="6.shtml">Official Symbolism</a></li>
<li id="navpart7"><a href="7.shtml">Laws of Adoption</a></li>
<li id="navpart8"><a href="8.shtml">Laws of Emigration</a></li>
<li id="navpart9"><a href="9.shtml">Rights of Foreign Nations</a></li>
<li id="navpart10"><a href="10.shtml">Rights and Powers of War</a></li>
<li id="navpart11"><a href="11.shtml">Treason or Secession of a Nation</a></li>
<li id="navpart12"><a href="12.shtml">Rights of the People of the Five Nations</a></li>
<li id="navpart13"><a href="13.shtml">Religious Ceremonies Protected</a></li>
<li id="navpart14"><a href="14.shtml">The Installation Song</a></li>
<li id="navpart15"><a href="15.shtml">Protection of the House</a></li>
<li id="navpart16"><a href="16.shtml">Funeral Addresses</a></li>
</ul>
</nav>

And the CSS:

#navigation a {
  /* Rules for navigation items */
}
#navigation a:hover {
  /* Rules for navigation items */
}

/* Rules specific for "you are here" */
#navigation #iamhere a,
#navigation #iamhere a:hover {
  /* Rules for the "you are here" item */
}

And the JavaScript (using jQuery) that finds the correct navigation item and sets the id attribute value to "iamhere":

$(document).ready(function(){
  var mybodyid = $('body').attr('id');
  var mynavid = '#nav' + mybodyid;
  /* e.g. for 3.shtml:
      mybodyid is 'part3'
      mynavid  is '#navpart3'
   */
  $(mynavid).attr('id','iamhere');
});

Clamshell Navigation

clamshell

<script >
$(document).ready(function(){
  console.log("Ready!");
  var mybodyid = $('body').attr('id');
  var mynavid = '#nav_' + mybodyid;
  console.log("mybodyid is " + mybodyid);
  console.log("mynavid is " + mynavid);
  // Set iamhere id
  $(mynavid).attr('id','iamhere');
  // hide all nested lists
  $('#navigation ul ul').hide();
    // show parents of "iamhere"
  $('#iamhere').parents().show();
  // show children of "iamhere"
  $('#iamhere').children().show();
});
</script> 

JSFiddle Example

Note for the JSFiddle example, we are using a 'div' to contain the 'id' instead of the 'body'.
Clamshell Navigation in JS Fiddle

Files