Assignment Instructions and SW Recommendations
All students need to complete some of the assignments listed on this page. Web-casts will initially cover two assignments per week. Consult syllabus for special course grading option.
H0 Intro Orientation
H0 Permalink - Permalink working best with Firefox/Cyberfox, a permalink sets a permanent link to this H0 assignment . So if you web surf to canvas or another external location and click the back button, it will automatically open the accordion for this assignment. Just click H0 Permalink and see what happens in browser's address bar.
Complete the five steps at https://cim.saddleback.edu/~class/cimRoot/de.html
Watch a prerecorded Web-casts = details on Canvas to open Canvas web-casts right^click open in new windows.
Two biggest mistakes students make in this class:
- Do not, try to complete all assignments at once, just work on one assignment at a time top down, complete this H0 assignment first, before starting H1. Both canvas (quizzes and videos) and assignment page are organized top down. Start at the top and work down. So on canvas intro quiz is listed first, intro webcasts are also listed first.
- For the orientation webcasts we are looking at the entire semester, but after orientation stick with one assignment at a time work top down. Also looking forward, starting with assignment H3, you will have to complete an online journal notebook. From H3 forward make sure you complete essay questions. Increasing your vocabulary is one of the best ways to master new subjects.
Checklist:
- Make sure school e-mail has been forwarded or will be checked
- Watch the generic course intro videos at https://cim.saddleback.edu/~class/cimRoot/de.html
- Complete the Questionnaire. You need to enter a non academic e-mail.
- You may want to also sign up concurrently for cimw115 Dreamweaver/WP remember prior preparation prevents poor performance, this class covers a lot of important material, students without proper preparation will not come close to getting the benefits of this course.
- Login into Canvas take quiz 0;
H1 Create Your CIM Home Page & Configure Firefox Web Development
H1 Permalink - Click permalink so H1 will open when you surf back and forth.
Web Page Assignment: Create a default home page on cim.saddleback.edu, Canvas has a video on using either Dreamweaver or FileZilla with cim. You can start with this index.html page.
I will be using Mozilla Firefox. Firefox was the first browser to integrate Firebug as the inspect element. To use firebug.next just Right^click select inspect. Other browsers have also integrated their own version of Firebug. For debugging JavaScript, first activate the Firebug copy-cat by typing right^click inspect. The inspect panel's has the JavaScript console window, just click the console tab. The console tab will display errors with line numbers and also allows you to type JavaScript code.
You can add the Web developer add-on has three checks in upper left corner, they represent HTML, CSS and JavaScript syntax checkers. HTML5 validators are still considered experimental. Web developer syntax check icons will print an exclamation mark or x when syntax errors are present. Future assignment have Canvas videos on JavaScript console and using inspect (right^click inspect).
Refer to these Live Examples for help:
- Basic HTML Document
- Basic Link example
- Tips on using Inspect aka Firefox Developers Tools
Checklist
- Make sure you have a home page on cim
- Make sure you have a working FTP access to cim, (FTP doesn't work from laptops on campus)
Optional Project
Project Permalink
Project Depending on What you do it Counts for 1 to 3 Homework Assignments
Reading Assignment: Review Project Web Page, you may want to ask questions in class about projects.
Try to decide on a class project - - Have added some new projects titles - react..js, vue.js, Bootstrap 4, and adobe Phone Gap may get popular.
Written Assignment: Create a web-based notebook journal web-page and briefly state your project. This is web-based notebook journal is just a web page. You can go back later an redefine your project.
We will be maintaining a web-based notebook journal, it is just a web page. You can also define, this page as a blog (aka Web-log). A log file is a file with a date followed by a note, they normally have multiple entries. A web-based log file created by a user is called a Web-log (aka blog). Application programs often maintain log files. On CIM multiple programs maintain log files. For example, Apache (CIM's Web Server) writes to log files whenever a Web page is accessed. You can view CIM web page statistics, the link just illustrated was created using Webalizer on Apache's log files.
Checklist
- Make sure home page has a link to your journal notebook - web page.
H3 -Tag Review & Basic HTML Validation
Watch HTML Canvas video and Web-casts. On canvas click Home tab, then click H3 and On Webcast Assignment Videos.
Traditional Reading Assignments:
- Gosselin Read part of Chapter 1 Intro to JavaScript on HTML or
- JavaScript Definitive Guide Preface
Answer questions 1..4 in your Journal Notebook (worth 0.5 assignment points) web page....
- Explain the difference between HTML, XHTML and DHTML. (Sample notebook journal with first two question completed)
- Explain the difference between the following doc type definitions: (HTML doctype is HTML5), and XHTML4.01 Transitional. Nota Bene, when HTML4.0 came out it had a few bugs so they quickly released the standard HTML4.01, which fixed the bugs. Therefore, the fourth version version of HTML is referred to as HTML 4.01. It is typical for software to do this.
- Why does HTML5, not have a corresponding XHTML standard?
- Briefly define the following tags: p, strong, table, td, tr, div, span, body, head, title, html,ul, ol, li. (You can use a web search, but try to define these tags from memory)

Your journal notebook needs to pass Nu HTML validation, or w3C Validator(not working w cim), once validated add the HTML5 validation icon. Note HTML5.0 validators are still experimental. But HTML 5.0 does have an official ICON. You may want to add the Firefox Web - Developer add on for validating files. CIMW 140 CSS discusses Web-Developer add-on,
Web Page Assignment (worth 0.5 assignment points): Create an HTML file, that has a table with three columns, column headers are: Extensions, Full Name, and Synopsis. The first column data should have the extensions (.css, .html, .htm, .js, .php, .sql). You will need to fill in the other two columns. The file must pass HTML 5.0 validation, you can use web developer add on, click menu topic tools menu item validate HTML which accesses the Nu HTML Checker. Note both NetBeans and Dreamweaver do auto validation.
Live Table Examples:
- Tables(jsFiddle) | Tables(codepen.io) tables start with the <table> tag, each row has a <tr> table row tag, each table cell has a <td> table data tag.
- Example adding table headers <th> a td tag that is bold and centered: jsFiddle | w style tag table headers,
Checklist
- Make sure you are familiar with HTML before continuing, review the HTML video a 2nd time if needed.
H4 JavaScript Engines, API and Document object
H4 Permalink - as usual Canvas has a recent webcast
Live Examples:
- JavaScript supports the standard escape sequences \n and \t; The escape sequence \n prints out a new line, \t goes to the next tab stop. In general the back slash \ (falls backward) escape the special meaning of the next character. Note double and single quotes have special processing (used to delimit strings), this examples illustrate back slash for printing ' and " inside a delimited string.
- The <pre> tag is the preformatted tag, it maintains the current formatting, example. In standard HTML formatting, multiple white spaces become a single space.
- Note jsFiddle is the most popular code playground, but doesn't support document.write, JavaScript hints and lacks console. You can use Chrome's console with jsFiddle, Firefox's console doesn't go to line number on errors. Another interactive code playground is codepen.io, has console and supports document.write, only problem with codepen.io you have to pay for more than 10 programs, previous example using codepen.io.
Journal notebook addenda (worth 0.5 assignment points)
- Good Article on JavaScript Engines. - duck assist AI, What are Spider Monkey and Chrome's V8.
- Wikipedia article on API. What does API stand for and represent?
- Compare two popular JavaScript API -and Google Maps API. With these two Java APIs Standard Edition, and a blackjack API written by me. Do you see any advantage to the consistent way Java does its API?
- Review these two API documentation examples: document, or w3Schools document API. Then describe two methods and two properties for object document. Note Document with the capital first is the interface (aka a Class that is implement, just the definition), the document with the lower-case letter first is the object, it actually exists. The object document is based on the interface Document.
Web Page Assignment (worth 0.5 assignment points): Create an HTML file with Hello World (hello.html) and your initials using JavaScript. Add four more document.write lines after Hello World, they should print out lines illustrated below and end your your initials using big letter (note my initials are Professor Tom DeDonno (PTD), yours is something else). The document.write method is usually avoided due to rewriting the DOM, however for an initial assignment document.write is a good stepping stone. Later on we will cover using both JavaScript getElement and jQuery sizzle selection to select an web page element and then change its content. If you know how to select elements do this, if not just stick with the basic document.write.
Hello World Hello CIMW 160 Hello JavaScript Good Bye Brought to you by...
Checklist:
- Make sure you home page has a link to the Hello World w your initials
- Review your web-based journal notebook and make sure it has 8 entries.
- Nota Bene, document.write changes the DOM so we should avoid using it, will learn about this later on.
H5 Chapter 1 Intro JavaScript
click H5 Permalink - watch the three Canvas Videos (use Firefox and right click^open in new window)
Read all of chapter 1 Gosselin or Definitive Guide - preface and chapter 1
Will be adding assignments from New Version of Book, you can do both books, or just new book or previous book edition.
Keep in mind its a points based class.
Live Examples From Text-book use:
7th edition cegage data files
6th using student data files (zip file may be blocked, if so right^click open in new tab)
(canvas has backup copies)
Introduction to JavaScript
I will be using Adobe Dreamweaver to demo this examples, you can use Aptana, - Eclipse, - Komodo, - NetBeans, - NotePad++, or Sublime
For Mac: Adobe Dreamweaver, - Aptana, - Eclipse, - Komodo, - NetBeans, - XCode, or TextWranger.
You can also use a JavaScript Code Playground discussed in H4.
Chapter 1 Viewgraphs and Data Files on Canvas
7th Edition Page 8 Figure 1-7
- Get student data Files above or on canvas, install to your local disk, install data folder
- goto chapter01 folder, move chapter to site root
- Open js01_txt.html
- in <head> add your credentials
- Save in site root at js01.html - review file and all linked files.
- <script> Example
- (page 12) With HTML code editor, add script beginning and ending tag between tag <figcaption>
Add this Document Write Example to your code, you can use one long document.write string using + string catenation or multiple calls to document.write, readability is always king.
Reminder JavaScript is case sensitive, Document is the interface, document is the object based on interface
- Save code and test
Book Errata saving as js01.html not s01.html, link should be https not http
- JavaScript has two comments in-line // and /* block multi line */ "C Universal Comments"
- (page 13) After script tag add:
/*
Information on available plants
including link to USDA website
*/ - after last document.write add in-line // hardiness zones for Chicago and surrounding area
- Variable Descriptions in Viewgraph
- page 16 Add three variables before ending script tag
//define variables containing plant file names
let blanket = "blanket.jpg";
let bluestem = "bluestem.jpg";
let rugosa = "rugosa.jpg"; - Expressions
- salesTotalFigure119.html define three Variables w calculations
Best Practices- Never use document.write, create a known HTML structure and access.
- Put all JavaScript in separate Files at beginning and end, short setup scripts specific to file at end are okay
- With script tag attribute defer (load HTML) then JavaScript, same as putting JavaScript at end or
Nota Bene, JavaScript may depend on HTML structure.
- async - parse HTML and JavaScript asynchronism the standard.
- We will do this when we rewrite this code using jQuery
- Page 25 - Test and Analyze Figure 1-21,
- If file js01b.js doesn't use contents of previous jsFiddle.
- Before </head> add <script src="js01b.js" defer></script>
Since we need HTML ID, we need read HTML for ids, so can use defer or put before </body>
Best Practice JavaScript in separate file, may need to put internal JavaScript code in <![CDATA[ .... ]]> Character data XML tag
Best Practice pay attention to IDE errors as they occur - example of not paying attention.
Convert book example to jQuery (Bonus Worth 1/2 Assignment Point)
- Since we will be using jQueryUI later, check jQuery UI for current version of jQuery to load.
- Get jQuery load script from top of this page
NetBeans Lets you select a JavaScript library,
Code Playground look for an Add Library (but they may just add script src tag)
jQuery.Major.Minor.bugFixes, Major is a Major Change, be cautions n updates. min use used minify the code
- Save js01_txt.html as js01_jQuery.html
- Save js01b.js as js01b_jQuery.js
- in js01_jQuery.html add a jQuery CDN load script in header block
- Move all java Script code to js01b_jQuery.js and add load script line before end of body
- replace all docment.getElementbyID with $( selector )
- jQuery provides an object $(selectXMLElement)or name jQuery(selectXMLElement)
- use Sizzle CSS selector
- CSS uses # to select XML element by ID
- We will be using two methods with jQuery object, either .click( Anonymous Function ) and .html( methods )
- Translate all document.getElementByID('id') to sizzle CSS select $('#id')
- replace JavaScript property with method .html( "string" )
- replace all $( "#blanket, #rugosa, #stemrose").click( with one call using this.getAttribute( "id").jpg as the src
Nota Bene, sizzle is standard CSS selector, anything you can select with CSS can be done with sizzle.
- You can use console to test sizzle selection
- replace document.write with $("sector").html("htmlString") or .text("string");
- Save and test
6th edition
6th edition page 12 Figure 1-2, Open Chapter01/Chapter/plants.htm and analyze file (browser view source);
Author used single quotes for link attributes, may want to fix this to double quotes.
Note that we use tingleyhand.css for display with only 999px max; tinley.css for displays with at lest 1000px
Can use DW scrubber or Firefox Resize-->View Responsive Layouts not seeing much of a difference
Notice author is using CSS for mouse rollover :hover
Note author is using HTML5 semantic tags
Programming Languages use compilers to translate to an machine like intermediate language. The intermediate language file is later dynamically executed.
- save as plants1.htm
- Add script tag to inside tag article > figure > figcaption
(not > is CSS selector for child; we often use space descendant)
Best practice add type="text/javascript" - Add document.write with "<p>Plant choices</p>"
- Notice Plant choices only appears in DW live view, not design view
- Modify document.write to display: Plant choices for hardiness zones 5a-6b as one paragraph line
- Add both multi-line /*.. */ and in-line comments // zones 5a-5b are Chicago and surrounding area
- Open your plants1.htm
- article > figure add image tag <img src="#" width="640" height="400" />
- add Script block in head block,add src variables pointing to three images...
var blanket = "images/blanket.jpg"; var bluestem = "images/bluestem.jpg"; var rugosa = "images/rugosa.jpg";
We also want to identify img tag using HTML id attribute set img id="plantImg" - Save file, later on we will add the actual swap image on rollover
Understanding Events - jQuery Version
- codepen.io Event example salesTotals - use inspect console look for error and repair, event="event-handler JavaScript code"
- Better version of salesTotal1.html with events, and no document.write, using getElementById( );
- Add onclick event to aside ul li each element
- Open plants1.htm
- add event attribute onclick="document.getElementById('plantImg').src = blanket;" to blanket Flowers
- onclick="document.getElementById('plantImg').src = rugosa;" to Hedge Rose
- onclick="document.getElementById('plantImg').src = bluestem" to Little Bluestem
- Save and Test file
- Move Images variable to right before ending body tag,
-
Best Practices:
- minimize JavaScript code inside body,
- Best places: head block preferably as separate file, or right before </body>
- avoid document.write, use element pointers
- use jQuery version
salesTotal2.html - don't worry about learning jQuery now, we will cover it later, best way to learn jQuery is to first learn JavaScript, basics matter - 2017 Super Bowl
Structuring JavaScript behavior/actions in separate file, modernizer
- Create separate JavaScript file for plants1.html
- Create plants.js
Add descriptive comment like:
./* JavaScript 6th Edition 2 Chapter 1
Tinley Xeriscapes 6
Author: Professor Tom DeDonno
Created 7/17/2017
*/ - - 4. Get JavaScript variable declaration code from plants1.html and paste into plants.js
Short-cut Keys Ctrl^A select, Ctrl^C copy, Ctrl^X cut, Ctrl^V is paste, or right^click - Save as plants.js
- Add script src tag before </body>
<script src="plants.js"></script> - Save as plants1.htm
- Create plants.js
- Libraries - provide code that everyone needs, jQuery easier to select and act on XML elements, modernizer feature detection and modernize some browser for HTML5
- Add and use modernizer library to plants1.htm
- Test plants1.htm inside IE prior IE8 - will use netRendering, Note Juno, AOL, and Illuminate use IE7 no HTML5.0 support save as plants2.htm
- In head block add a local customized version of modernizer
<script src="modernizr.custom.05819.js"></script> - Validate Web Page plants2.htm using either Dreamweaver (bottom icon) or go directly to W3C Validator
Instead of using device-min-width, use viewport min-width and max-width
Add water-wise h3 headers first child of article tag.
Web Page Assignment (worth 0.5 assignment points, js01 bonus 0.5 points):
- Complete hands on project 1-1, 7th edition page 31 cengage 7th edition data files (copies also on canvas) or 6th Edition page 65-66 - student 6th Edition data files
- Complete hands on project 1-2 7th edition page 32 or 6th edition page 66-67
- Bonus worth 0.5 assignment complete js01.html as jQuery (you can use above example)
- Make sure you home page links to both assignments
Journal notebook addendum (all answers are in textbook chronologically - worth 0.5 assignment points0)
- What is a a scripting Language?
- What is ECMAScript?
- How do you create a single-line "line" comment in JavaScript?
- How do you create a multi-line "block" comment in JavaScript?
- What is the Document Object Model?
- What does W3C stand for, what do they do?
- What is a three-tier (aka multi-tier or n-tier) Client/Server system?
- What is a variable and identifier?
Complete Canvas Quiz 1 Intro JavaScript ( Gosselin Chapter 1, or JavaScript Definitive Guide Preface and Chapter 1)
H6 Chapter 2 Intro JavaScript data types, operators, expressions.
click H6 Permalink and watch Canvas Webcast(right click^open in new window)
Traditional Reading Assignments:
- Gosselin, First half of Chapter 2 Functions, Data types and Operators or
- JavaScript Definitive Guide: Chapter 2: Lexical Structure, Chapter 3: Variables and Data Types chapter 4: Expressions and Operators
Second Edition of Definitive guide JavaScript Data Types Chapter 2 Online,
7th Edition Example (Objective: create Fan Trick Page and set defaults)

- Make sure you have the 7th edition data files, they are on canvas and links in previous assignment
- goto data ffolder chapter02 js02 data folder
- open js02_txt.html
- Fill in date and name in comment header
- Analyze the document
- Save file as js02.html (don't update links) in your public_html folder, can create subfolder, may need to copy supporting flies
May be easiest just to copy chapter folder
as chapter2 - Test page in browser, (add values in web form) on Reload notice values are erased
We want to have defaults set in form elements
- Set form defaults with HTML attribute value="default", or attribute checked
- Code Pen js02 File
- Create file js02.js with above setupForm function
- Add link to js02.js from js02.html
- Calling a Functions, by default all function return either void or a value; - Notice Math.sqrt( 24 ) returns a value, showStatus doesn't
- Add load event listener to that calls setupForm on load
- In js02.js window.addEventListener( "load", setupForm );
- Test changes
- Page 41 add four constants to js02.js
const EMP_COST = 100; //cost of photographers per hour
const BOOK_COST = 350; //cost of memory book
const REPRO_COST = 1250; //cost of reproduction rights
const TRAVEL_COST = 2; //cost of travel per mile - Page 60 estimate the total cost of service - analyze code for getEstimate jsFiddle (use Console look for errors)
- Add getEstimate function to your js02.js testing using console window
- to get set/unset clear, we just use HTMLObject.checked;
- Page 62 - add checkbox to js02.js from jsFiddle (use Console look for errors)
- Look for id="estimate" in js02.html, this will become the dynamic estimate
- before return in totalCost, set id estimate
document.getElementById( "estimate" ).innerHTML = "$" + totalCost;
nota bene, we added return totalCost for testing
- Page 63, added getEstimate(); call to end of setupForm function
- We want estimate to change as user updates the form, to do this add onchange event handler to each input form element
- jsFiddle with eventHandlers, test and add to end of setupForm
- Test File in Browser, also make mistake in file and check console window
7th Edition rewrite js02.html to jQuery js02_jQuery.html
- copy js02.html to js02_jQuery.html
- in js02_jQuery.html header Load jQuery CDN identical to js01b_jQuery.html, why?
- cp js02.js to js02_jQuery.js, copy js012.html to js02_jQuery.js
- Move link to end of js02_jQuery.html to js02_jQuery.js, js02_jQuery.html has only two JavaScript links, no JavaScript code, CDN in header, local js code at end.
- Modify the code getEstimate function to jQuery
Best Practices JavaScript Variable Names, constants and HTML ID should match, Do This?
$( Selector ).val(); and $(Selector).checked property can be used to set, and check check boxes;
$( selector ).prop( "checked", true or false ); $( selector ).prop( "checked" ); returns current value of check box
- Test getEstimate
- Use Sizzle selector, to select or form elements, $(selector).change( getEstimate );
- Add setupForm code as anonymous function to $(document).ready( function() {... } );
6th Edition Working with Functions:
- 7th edition data files are on canvas, you may complete any 7th edition example in chapter 1 in place of this 6th edition.
- Basic Functions, notice you can execute calculateSquareRoot( 16.0 ) from console. (current version jsFiddle doesn't have console)
- Page 77 Chapter 2, (Update totals on a web page depending on form selections)
- Open estimate.htm
- Update author/date header save as estimate1.htm
- scroll through and analyze document
Copied File to new folder, you need copy all local files to new location
- Test document notice forms don't update totals
- Make form changes -
- hit refresh/reload button (shift F5) values may or may not update
- open ft.js save as ft1.js (add link before </body> in estimate1.htm )
- Add this code:
// sets all form field values to defaults function resetForm() { document.getElementById("photognum").value = 1; document.getElementById("photoghrs").value = 2; document.getElementById("membook").checked = false; document.getElementById("reprodrights").checked = false; document.getElementById("distance").value = 0; }
- Add link to ft1.js before </body> (Will link to resetForm next)
- Test function calls, and passing arguments.
- Chapter 1 salesTotal example, Handling events,
- SalesTotal3.html Can put all JavaScript code in one location, using element.event=event-handler where event-handler is JavaScript code (e.g., function call)
note also use element.addEventListener( "event", function, true|false); - In jQuery we add a listener (e.g., salesTotal2.html).
- Add Event handler to call resetForm
- Open ft1.js
- add on load listener, document.addEventListener("load", resetForm, false);
Nota Bene,- JavaScript is a single pass interpreter it is not a multi-pass compiler.
- The second problem is that both unload and load event may be deleted by browser.
- so for your final version don't use..
- document.addEventListener("load", resetForm, false);
- //instead we will put
- resetForm( );
- // at the end of the JavaScript code.
- //for jQuery we are alway using $(document).ready( function() {...}
- /at the end of the java Script code.
- Save all and test estimate1.htm
- Call resetForm using the inspect/console window
- Delete closing brace for resetForm function, can you find error with the (right^click inspect console tab ) console window.
"use strict"; directive tell system to use strict JavaScript, must declare variable etc. Dreamweaver lint turn it off - Default functions return 1 value, averageNumbers returns average of three number,
- Variable scope, always use var first time you declare a variable, variable exists only in block it is declared in, outside block its global -averageNumbers
- NaN is a type, jsBin has more detailed console - better practice version - Note for PTD, with jsBin make sure you clone and delete (it kills original)
- Variable Masking
- Add Global Variables to ft1.js
- Open ft1.js
- // global variables
var photographerCost = 0; var totalCost = 0; - Save and verify global variables exist using inspect console
- Use built in Console input, type slow, look for built-in "intrinsic" JavaScript functions: eval( JavaScript Code ), parseFloat( String ), isNaN( number ); parseInteger( String );
Working with Data Types page 91
- A variable, has a name "identifier", value, the value is of a specific data type, a data type is dependent on the language primitive types.
- JavaScript has the following primitive types: number, Boolean, string, undefined, null - basic loosely typed example
- JavaScript is dynamically typed (aka loosely typed) types is set when variable is set,
- Programming languages are strongly type, or static typed, types are set at compile time, when we first declare a variable.
- JavaScript uses 54 bits for numbers, it mixed both integer 253 to -253and floating pointing.
- Wrapper class Number has all constants Number.MAX_SAFE_INTEGER = Number.MIN_SAFE_INTEGER, use console explore Number Class - also try out 2/0.
- Primitive primary JavaScript data types String, Number, and Boolean.
- Check box return true or false, checked or not checked. Add two boolean variables to ft1.js
- Open ft1.js
- below var totalCost=0; add....
var memoryBook = false;
var reproductionRights = false; - Inside resetForm( ) update check box defaults with global variables just defined.
document.getElementById("membook").checked = memoryBook;
document.getElementById("reprodrights").checked = reproductionRights;
- String - often array of characters we begin and end Strings with double quote ". Notice + is either plus or String catenation.
Using Operators to Build Expressions.
- Arithmetic Operators ( +, -, *, / and % ) example.
- JavaScript will translate string to number automatically, but when it sees a string default operation is String catenation.
- Auto Increment, Auto Decrement ++n same as n += 1 same as n = n + 1;
- Assignment Operator "=", calculate right hand side or equation, and set left hand value to it.
Assignment variable often used in equation, so n = n - 2; is written as n -= 2; using compound operator - Add function to calculate cost of hiring Photographer
- Open ft1.js
- Add function calcStaff() { .. }
- Inside function...
var num = document.getElementById("photognum");
var hrs = document.getElementById("photoghrs"); - totalCost -= photographerCost; //clear out previous cost
- photographerCost = num.value * 100 * hrs.value;
- totalCost += photographerCost;
- document.getElementById("estimate").innerHTML = "$" + totalCost;
- add calcStaff() to end of resetForm() when we load page we need a new calcStaff
- Add Listeners so when we change a value we get a new total
function createEventListeners() {
document.getElementById("photognum"). addEventListener("change", calcStaff, false );
document.getElementById("photoghrs"). addEventListener("change", calcStaff, false );
} - Add createEventListeners to resetForm
- Save Changes ft1.js
- Test estimate1.htm (verify it works)
Journal notebook addendum (0.5 points):
- What is the difference between a named function and anonymous function.
- Why do we use anonymous functions?
- How do you check JavaScript errors in a browser?
- Contrast the three keywords const, let and var (use your own words in your journal)
Web Page Assignments (0.5 points):
- Complete Fahrenheit to Celsius (7th edition page 71-72 6th edition pages 94-96)
Bonus worth 0.5 assignment points add absolute 0 kelvin to previous assignment
- 7th Edition Complete Hands on Preojct 2-4 page 74 or if using
6th Edition Complete Hands on Project 2-1 pages 138-140
.
H7 Chapter 2 Comparison and Conditional Operators
H7 Permalink and watch Canvas Webcast(right click^open in new window)
Traditional Reading Assignments:
- Gosselin, First half of Chapter 2 Functions, Data types and Operators or
- JavaScript Definitive Guide: Chapter 2: Lexical Structure, Chapter 3: Variables and Data Types Chapter 4: Expressions and Operators
- 7th edition data files are on canvas, you may complete any 7th edition example in chapter 1 in place of this 6th edition.
6th Edition
Comparison and Conditional Operators
- Comparison or Relational Operator compares to values returns true or false
- Conditional Operator, condition ? true Expression To Execute : false Expression;
- Update total Cost when user select memory book or reproduction rights
- Open ft1.js
- add...
function toggleMembook( ) {
(document.getElementById("membook").checked === false) ? totalCost -= 250 : totalCost += 250;
document.getElementById("estimate").innerHTML = "$" + totalCost;
} - add...
function toggleRights() {
(document.getElementById("reprodrights").checked === false) ? totalCost -= 1250 : totalCost += 1250;
document.getElementById("estimate").innerHTML = "$" + totalCost;
} - Add two more listeners to createEventListeners...
document.getElementById("membook"). addEventListener("change", toggleMembook, false);
document.getElementById("reprodrights"). addEventListener("change", toggleRights, false); - Save all work, test estimate1.htm (450 + 1250 = 1700);
- falsely types are types translated to false when used as boolean. All other dynamic types become true, best practice we don't mix types, but programmers use short-cuts all the time. For languages not enforcing type-checking, aka scripting, In general 0 is false non-zero true.
Operator Precedence
- Understanding Operator Precedence: parenthesis, methods, Grade school math * / + - , =
- Modify calcStaff() to include mileage charges
- Open ft1.js
- in calcStaff() Modify photographerCost to include distance.value * num.value;
var distance = document.getElementById( "distance" );
photographerCost = num.value*100*hrs.value + distance.value*num.value; - Add another listener to createEventListeners
document.getElementById("distance"). addEventListener("change", calcStaff, false); - Save ft1.js and test estimate1.htm; change hours from 2; enter distance 50 (should see change of $100)
jQuery update of estimate.htm
- first copy over estimate1.htm to estimatejQuery.htm
- Cleanup HTML, get rid of aside by moving id="estimate" right after form
- Optional Best Practice: Set all HTML elements with default values, add reset button, drop reset false variables
- Load jQuery cdn <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> before modernizer
Load link to ftjQuery.js before </body>
remember cim is not an https server you need to use http on cim - copy ft1.js to ftjQuery.js
- Test your new estimatejQuery.htm
- Best Practices: translate negative to positive, if( x ) is better than if( x == false ) or if( !x )
- Translate document.getElementById( "xyz" ) to $( "#xyz" );, when possible simplify to fewer variables
- Translate .val to chaining methods $("#xyz").val();
- Update .innerhtml to the jQuery method $("#id").html( string );
- Can use .is( ":checked" ) or JavaScript code on conditionals
- Drop resetForm code
- Move addEventListener calls to on ready callback $(document).ready( function () { ... } );
- Change all addEventListener to $( selector ).change( event-handler );
- Combine selectors
- Move all once use functions into anonymous functions
Notebook Journal Addenda
- What is a comparison operator? What kind of values does it return?
- How is the expression 5 + 2 * 8 evaluated? Explain your answer.
- With jQuery how do you select more than one single ID element at a time?
- From web page assignment, give and briefly describe an example of jQuery chaining.
- How do you avoid using document.write on a web page?
Web Page Assignments
- 7th Edition complete js02.htm (completed in h6) or 6th Edition Complete the estimate1.htm as done in webcasts and in book
- Rewrite js02.js in jQuery (completed in h6) or for 6th edition rewrite estimate1.htm to jQuery
Possible Browser Incompatibilities
document.addEventListener'(load',....) does not refresh the form on page reload in Firefox. It does in Chrome and Opera. So instead I am using window.addEventListener("load", resetForm, false) in ft.js. This works with Firefox, Chrome and Opera.
In ftjQuery.js, after converting the code to jQuery, I find that I have to use resetForm() to refresh the form on page reload in Firefox - inside document.ready(). So I have not removed the code for resetForm().JavaScript is a single pass interpreter it is not a multi-pass compiler.
The second problem is that both unload and load event may be deleted by browser. so we will not be using statements like this...//document.addEventListener("load", resetForm, false);
//instead we will put:
resetForm( );
// at the end of the JavaScript code.// for jQuery we are alway using $(document).ready( function() {...}
// at the end of the JavaScript code.
Checklist:
H8 Chapter 3 JavaScript Array Object and Control Structures, jQuery example
H8 Permalink and watch Canvas Webcast
Traditional Reading Assignments:
- Gosselin Chapter 3 Building Arrays and Controlling Flow or
- JavaScript Definitive Guide: Chapter 5: Statements; Chapter 6: Functions; Chapter 8: Arrays
- 7th edition data files are on canvas, you may complete either 6th or 7th textbook example
7th Edition page 80
- goto Data Folders/Chapter03/js03/chapter folder, copy contents to your local site root
I'm using new folder chapter3 - Open chapter3/js03_txt.html, update/analyze save as js03.html
- Open js03_txt.js save as js03.js
- Analyze and Add weekDays. to js03.js
- Open file schedule.js and Analyze
- Add src links to js03.html
<script src="schedule.js"></script>
<script src="js03.js" defer></script>
Nota Bene, with best practices we would add a $(document).ready event to end of html document
- Page 86 analyze arrays using console window on js03.html, using console window answer
- how many elements in gameDates?
- display contents of 5th item in gameOpponents
- display contents of 5th item in gameResults
- document.links.length is an HTML collection of page links
- document.links[1].innerHTML
- gameOpponents[23] returns undefined why?
Will need knowledge of flow control to use arrays and populate calendar
- I cannot find page where author completed this assignment?
They completed assignment in the bottom half of my PDF, which I didn't see on the screen.
You can complete using my notes/webcast on page 88, I'm using function name addColumnHeaders, book using addWeekDays.
- Work top down on above image, first Populate the weekDays, jsBin
- To fill in calendar notice the td id values and the array gameDates match.
We need to select each one read inner HTML and add new data. after H1 date Header
Another method is we could create a new HTML element and add it as a child of each td (next sibling of h1)
Insert is before; Append is After
Textbook page 93-94 create gameInfo string in function showGames(),
document.getElementById( gamesDates[i] ).insertAdjacentHTML( "beforeEnd", gameInfo);
- Need to add vs or @ before opponent name, gameLocations home is vs, away is @
good time to use conditional operator (gameLocations[j]== "h" ? "vs." : "@" )
Author page 99 used an if/else condtion, but conditional operator is better.
- Second line add W or L and [ runScored - runAllowed ](just usiing a gameResults, runsScored, adn runsAllowed)
- Add innings in parentheses when not exactly 9, gameInnings != 9
Author used [innings]*** when less than 5, page 100
- Set background colors, green for win, red for loss, Analyze CSS code to get actual colors
Upon Analysis - Set new element as p with class names win, loss, postponed, suspended, going to use element.classList.add( "win" );
You can use a switch, or send up a new array with the four values and compare first letter
page 106 they set gameInfo paragraph p tag to the right class.
- Note for postponed the CSS should take care of inverted text (always check)
7th Edition jQuery Translation
- copy js03.html to js03_jQuery.html
- in js02_jQuery.html header Load jQuery CDN identical to js01b_jQuery.html, why?
- copy js03.js to js03_jQuery.js
- Update link in js03_jQuery.html to js03_jQuery.js (drop defer keyword)
- In schedule.js update arrays to const, weekDays should be in schedule or we should have just one javascript File
- Best move schedule arrays to js03_jQuery.js
- drop both functions names, and add $(document).ready( function() { will code for both functions } );
- Optional keep function names, put all array inside ready, call three function at end
- Test js03_jQuery.html
- Translate the th header to a each( function( index, element ) { $( element ).text( weekDays[index] ); }
- Test make sure weekdays are printing
- Use $("table#calendar tbody tr td").each( function again
- Create element with just $( "<p></p>" );
- Use method this.getAttribute( "id" ), to get id.
- Use element.addClass( ) to add class
- jQuery used append to add element after, prepend for before.
with element $( "td#" + this.getAttribute( "id" ) ).append( e );
6th Edition
Arrays
- Basic Array Example
- Advance Students JavaScript array is an Object, we can use new Array(6), the array is both a queue (shift) and stack( push/pop ).
- Setup August Schedule for Tipton Turbines
- Open Chapter03/Chapter/calendar.htm save as calendar1.htm
- Analyze document structure, note ids 8-1
- Make sure calendar1.htm passes validation replace device-width with min-width (best practice use viewport not device)
- Use either DW or Browser Inspect to verify responsive design modes.
- Create file tt.js, add link right before </body> tag
- using Analyze arrays,
- Analyze code
- With jsBin console verify length of each array & test the lines below
- var list = document.getElementsByTagName("li"); return and why?
- for( i=0; i < list.length ; ++i ) list[i].innerHTML = daysOfWeek[i]
- add all three arrays to tt.js.
- Save and upload calendar1.htm (tt.js)
Flow Control Repeating Code
- Add Column Headers for Weekday names to Calendar Header
- Analyze this while loop
copy AddColumnHeaders to clipboard - Add addColumnHeaders function to tt.js
- add Listener to call addColumnHeaders on load
window.addEventListener("load", addColumnHeaders, false);
- Analyze this while loop
- Add days of month 1..31 to calendar
- Analyze this do while Loop - Same code in standalone daysOfWeek web page. (Console easier to work with in webpage)
- Get addCalendarDate function add to tt.js
- Create function setUpPage( ) {
addColumnHeaders();
addCalendarDates();
} - Call setUpPage just one alter previous, window.addEventListener to call setUpPage().
Note you don't need the object window, everything is already tied to window
window describes the entire web page, it has the object window.document.writeln(..);
- Add for loop for adding gameInfo
- Analyze this for loop
- Add addGameInfo function to tt.js
- Add call to addGameInfo in setUpPage( );
- Add @ before aways games, and vs for home games
- Analyze this if statement
- Add the new addGameInfo function to tt.js
- example, switch( integer or string ) find matching case statement.
- Previous example daysOfWeek web page. had conditional operator
- Translate tt.js to ttjQuery.js
- Save calendar1.htm as calendar1jQuery.htm update link to ttjQuery.js
- Add jQuery CDN like last time <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
- translate all getElementsByTagName to $( "tagName" ) - using standard CSS node selector, sizzle selector
- Replace innerHTML with jQuery .text method, we use .append to add text and .html for HTML code.
- Comment out event Load, tests three modules
- Add more sizzl;e selectors: space is descendant, #id, "#id p:nth-child(2)" select the 2nd p tag inside #id
- Test all three methods
- Best Practice use for loops over do while, and also while with incrementing.
- Try out each method with addColumnHeaders
$("th").each( function( index ) { $(this).text( daysOfWeek[index] ); } );
- make setUpPage $(document).ready( function() {...} );
- Can combine addCalendar dates inside the gameInfo as the first item under loop
- Can make all functions anonymous functions
- Consider Conditional operator string to replace switch statement
Web Page Assignments
- Complete either 7th edition js03.html or 6th edition calendar.htm as done in book and webcast (optional case vs if statement).
- Translate either 7 edition js03.html or 6th edition calendar.htm to jQuery js03jQuery.html/js03jQuery.js or calendarjQuery.htm/ttjQuery.js respectively.
Journal Notebook Addenda
- How do you access an individual element in an array?
- What property do you use to determine the number of elements in an array?
- How do you use a browser to check the value of a specific array element?
- Briefly describe the Array object, discuss four of its methods and two of its properties.
- Briefly discuss the looping flow Control structures (for, while and do while).
- What are the differences between a while and do/while statement?
- Which repetition statement allows you to initialize a counter variable as part of its syntax?
- Briefly define the branching flow control structures if, if else and switch/case statement.
Checklist:
- Complete Canvas Quiz 3 Functions, Events and Control Structures
- Make sure your home page has assignments up to H8 completed and linked.
- Review your Journal Notebook
H9 Chapter 3 Optional
H9 Permalink and watch Canvas Webcast
7th edition data files are on canvas, you may complete any 7th edition example in chapter 1 in place of this 6th edition.
7th Edition, create a calculator either postfix or infix.
Web Page Assignments
- 7th Edition Hands-on Project 3-1 or 6th Edition Hands on Project 3-1
- 7th Edition Hands n Project 3-2 or 6th Edition Hands on Project 3-2
or instead
Complete either a in-fix calculator | in-fix calculator 2 with at least 10 functions, negative and floating point numbers
or an HP post-fix calculator, do have a JAVA API for a MVC Hp Calculator.
Web Page Assignments - but you must complete H8 first before you can get credit for H9 - H11 will have two sets of assignments for both novice and programmer
- Complete hands On Project 3-1 Page 205, error in book (aka errata) on page 206 Item 7we need to use typeof method,
So item 7 becomes:
PS attachEvent has been deprecated, so we only need the one lineif (typeof submitButton.addEventListener === "function" ) { submitButton.addEventListener("click", calcTotal, false); } else if (typeof submitButton.attachEvent === "function" ) {
submitButton.attachEvent("onclick", calcTotal);
}submitButton.addEventListener("click", calcTotal, false);
- Complete hands-on Project 3-4 Page 209 - Canvas has a 10/26/22 webcast
Bonus points translate Project3-1 and 3-4 to jQuery, Add to items to the menu items in Project 3-1.
H10 Chapter 4 Debugger & Array Review
H10 Permalink and watch Canvas Videos
Traditional Reading Assignments:
- Gosselin Chapter 4 JavaScript Debugger and take Canvas Chapter 4 quiz.
Watch the Canvas Video on JavaScript Debuggers
You should be able to do assignment and journal after Canvas video, if you need more help these Live Examples will help:
- JavaScript W3Schools Date, once again they may move the Date live view example - may want to use the JavaScript console to check error messages.
- Review HTML element example, - getElementById documentation (will see document.getElementById in h9).
- Random Number discussed above
- Typical for loop, use the example and try to write a for loop to print 10 random numbers, that are also stored in an Array.
- Function Call.
- Sort Array First example, lexicographically Further down example on numeric sort by passing a compare function.
Example js04

Copy data files, drop _txt, fix 4 syntax, add "use strict";
- Copy datafolder/Chapter04/chapter to your site root - chapter4
- Using chapter4 in your site root
- Open js04_txt.js save as js04.js
- Use your IDE and fix the four syntax errors in js04.js,
File has 4 syntax errors: Line 18 let instead of et Line 27 missing = sign Line 28 missing " double quote Line 70 missing ( You want green lights on either DW or NetBeans )
In general, JavaScript interpreters stops at first syntax error.
- If needed, Finish fixing errors by using console, inspect dialog window
- Open js04_text.html save as js04.html
- Analyze js04.html - check out HTML warnings
- Way Author intends to write program for verifying data is pretty bad,
You need to use HTML 5.0 attributes, RegEXP, and callback functions - Page 126 add "use strict"; at line 1;
- with strict with Inspect all variables need to be defined first missing let at line 16
Tractor Acres Months Other
E2600 <=5000 <10 E3250 <=5000 >10 W1205 >5000 <10 W2500 >5000 >10 wheat, corn and soy W2550 >5000 >10 Often prudent add comment in english
/* E <= 5000 acres; W > 5000 acres */ Make sure right tractor relative acres and months is displayed.
- You can add above table to javaScript file, but HTML doesn't render in JavaScript
- page 130, enter 5 acres and 8 for months; response is W1205E (for large farm)
add alert( "First If Block " + acresBox.value + " acres" ) or console.log right after first if statement in createRecommendation( );
for else clause use alert( "else block " + acresBox.value + " acres" );
also test 5001 - We know that if/else is working as programmed
- Logic error it should be acres <= 5000 in first if block
small sized tractor E2xxx for some farms
- Debug number of months, +10 months heavy duty, for less light duty tractors.
- Open Inspect, Sources
- Left most icon is the inspect element,
- Three-dot meatball (horizontal) or vertical are the navigation menu
- Page 137, bring up js04.html, and open up inspect, console, debugger and source panels,
Experiment with the three dot view menu ⁞ ,··· and gear menu ⚙ - console/debugger windows can be moved almost anywhere - Page 138
Enter 100 acres; 12 months; from table above E3250 tractor
Add breakpoints to lines 101, 104, 109, 110 - At breakpoints check values of monthsBox.value
- Remove all breakpoints (right^click remove all)
/* suffix after tractor E for E85; B for Biodiesel; D for diesel */
- Page 142 add breakpoint to line 87 function testFormCompleteness() step into function.
- Page 144, we want fuel type suffix added to recommended tractor they should be:
E for E85, B for Biodiesel and D for standard diesel;
- Add breakpoint to line 123 (before if block for setting fuel and add messageHeadElement.innerHTML watch window
- Fix code so correct suffix is displayed, for document.getElementById( "E85" ).checked returns true when checked.
- Check out what is a call stack
- Verify correct tractor with suffix added is displayed.
Web Page Assignment
- Complete js04.html
- Create a program that creates a 11 element array consisting of 11 random integer numbers between 0 and 1000 inclusive. Print out the 11 random numbers original order, then ascending order, then then in descending order. You will want to use Array method sort. the print out average and median value of your array.
All programming language have a random method/functions that returns a random number from 0 to less than 1.0. JavaScript uses Math.random(). If one wants random numbers from 0..10, just multiple Math.random()*10 this would give a floating decimal number between 0 to 9.999, to make them easier to read just use Math.floor, (i.e., Math.floor( Math.random()*10) ). Therefore you would have a whole integer number from 0..9. For this assignment I would translate random number to integers they are easier to visualize.
Journal Notebook Addenda
- How is window.alert useful in debugging?
- What is console.log, in what two situations is console.log superior to window.alert?
- What is the difference between a watch and scope window?
Checklist
- Complete Canvas Quiz 4 JavaScript Debuggers
- Review your Journal Notebook
H11 Chapter 5 DOM
We will be creating a lightbox w a slider - do have a large collection of image viewers.
7th Edition Book Example
- Page 164 Get, Copy, rename _txt Files
- Goto your data folders/chapter05/chapter/js05 adn copy folder to your site root
- Open js05_txt.html adn js05_txt.js and save as js05.html adn js05.js
- In header, add links to three local files: lightbox.css, lightbox_data.js and js05.js, both JavaScript files are defer - we have been putting local js at end
- Make sure all variables have been defined and/or correct names
Replace imageCount with imgFiles.length; . - before </article> ends add <div id="lightbox" ></div>
- Analyze code, and Save
- Page 171, create lightbox nodes
- Analyze code in this jsFiddle, not JavaScript associative array
- Copy jsFiddle, code into js05.js
This jsFiddle has created an asociated array instead of five element, so e[ 'lbCount' ] is the variable lbCount in the textbook
- Verify 5 divs exists, and test associative array
Chrome Inspect Elements Tab; Firefox Inspect Inspector tab, you should be similar to figure 5-11.
- Page174 To add images to box iterate imgFiles array, Open js05.js
- at end code to iterate imgFiles
for( let i=0; i < imgFiles.length ; i++ ) { let image = document.createElement( "img" ); image.src = imgFiles[i]; image.alt = imgCaption[i]; e[ "lbImages" ].appendChild( image ); }
- Your should see first four iamges
- Page 175 set lbTitle, and lbCounter
use IDE and console to fix any syntax errorse[ "lbTitle "].textContent = lightboxTitle; let currentImg = 1; e[ "lbCounter" ].textContent = currentImage + "/" + imgFiles.length;
- Set the entities for lbPrev ◀ lbNext ▶ and lbPlay ⏯ using jsFiddle.
- Page 176 Save changes and verify operation with need HTML entities.
- Page 178 implement the next button, showNext() function - jsFiddle
function showNext( ) { e[ "lbImages" ].appendChild( e["lbImages"].firstElementChild ); (currentImg > imgFiles.length ? currentImg++ : currentImg = 1 ); e[ "lbCounter" ].textContent = currentImg + " / " + imgFiles.length; }
- In createLightBox function, we need to add handler for lbNext button.
e[ 'lbNext' ].onclick showNext; - Save all work and test (keep console inspect visible)
- page 180 implement showPrevious( ) insert lastchild before current first child
- Can copy code for showNext, use insertBefore( lastElementChild, firstElementChild) and decrement currentImg
function showPrevious( ) e[ "lbImages" ].insertBefore( e[ "lbImages" ].lastElementChild, e[ "lbImages" ].firstElementChild); //decrement the count watch for 0 (currentImg > 1?currentImg--:imgFiles.length); e['lbCounter'].textContent = currentImg + " / " + imgFiles.length;
- Add listener for showPrevious to e["showPrev"]
- Test previous and next, make sure console window is open
- Page 180 add 1.5 second timer, setInterval( showNext, 1500 );
- Save all work and tests next, previous and play (remember next does have console.log)
- The next require you to add an overlay, a popup model dialog box with a full size image on top of the current webpage. These are done on viewgraphs 25-43;
Web Page Assignment:
Complete js05.html which was done above, in book and also in canvas webcsasts.
H12A Update js04 to jQuery
Upgrade js04 to jQuery/HTML 5.0
- The authors version is spaghetti code, and when you try to translate it to jQuery you end up with spaghetti and meatball code.
- Use the steps below to create a clean code version, the one done 12/4/24 turn out to be spaghetti and meatball code.
- Our goal is to start almost from scratch and write clean code w best practices in mind.
- Implement the following Best Practices:
- fewer variables, (few global mainly constants)
- use const for constants
- HTML ID and Variable names should match
- take advantage of HTML5.0 (its an API)
- take advantage of jQuery, can search web $.inArray( "crop checked", [ "corn", "wheat", "soy" ] )
- repetitive tasks functions – complex function that work are great
- w scripting use console window for testing, APIs are strong - search web for help
- Open js04.html, js04.js save as js04_jQuery.html and js04_jQuery.js;
- if you didn't do js04, just go back to the data folders and get js04_text.html and js04_text.js; or
use this zip file - updates links in js04_jQuery.html and copy jQuery CDN link from previous assignment
- Drop all code in js04_jQuery.js except
- keep tractor model description but make them constants and drop desc suffix
- in createRecommendation function just display first tractor model description
createRecommendation add console.log( "starting createRecommendation" ); and $( "#tmessage" ).text( E3250 );
we will gradually add code to this function.
- in js04_jQuery.htm take advantage of HTML5.0 form strengths by reviewing this form example
- Implement title, min, max and/or pattern in HTML 5.0 code
- Add submit button, and on form tag add attribute onsubmit="createRecommendation(); return false;"
- Save and Test
- Best Practices: make repetitive tasks functions - okay for functions to be complex
- Create function setTractor( String name ); write tractor name and description to id="message" and id="messageHead"
function setTractor( name ) { $( "#messageHead" ).text( name ); $( "#message").text( eval( name ) ); }
- Replace $( "#message").text( E3250 ); with setTractor( "E3250" );
- Save and Test
- Best Practices use power of HTML 5 API, add required atttibute to acres and months.
-
Best Practices be aware of power of API
In console/inspect test ways to select HTML elements- tests var v = $("fieldset"); v.find( "#acres").val();
- Sizzle var f1=$("fieldset input#acres"); f1.val();
- $("fieldset:nth-child(1) input").val(); /* for array first element is 0, for nth-child its 1 */
- above we just used: $("input#acres").val(); val() example
var acres = $("input#acres").val(); var months = $("input#months").val(); //to createRecommendation
- Best Practices: fewer variables, write some code and test "divide and conquer"
- Add Acres $("input#acres").val() to create recommendation
- For acres less than or equal 5000 display first "E" tractor, for greater than 5000 acres display first W tractor
- Make sure you include comments /* acres <= 5000 use E tractor */ /* acres over 5000 use W tractor */
- Save and Test
- Best practices month and acres only where we need it - minimize global
- Implement months, < 10 E2600; >= 10 E3250; < 10 W1205; >= 10 W2550
- Note we added required attribute to input acres and months "Use HTML 5"
- Save and Test
- Add suffix of fuel type to tractor
- Add two ids to fieldset, fuel for fuel radio group, and crops for crop set.
- add attribute checked to HTML input element diesel
- test this in conosole window: $( "fieldset#fuel input:checked" ).attr( "id" ).charAt( 0 );
- Add the code above to setTractor header
- check ids wheat, corn or soy if set, set tractor to W2500
- $( "fieldset#crops input#wheat"
).is( ":checked" ) || $( "input#corn" ).is( ":checked" ) || $( "#soy" ).is( ":checked" )
all three versions will work, you are just being more specific on #corn, pointing to uinique HTML id on #soy.
- Save and Test
- In the books version, the moment you change a field, it updates the tractor name.
- Review this jsFiddle, and implement JavaScript code in your js04_jQuery.js, but remove acres2, & months2.
acres2, months2 are in place for testing difference between type="text ant type="number"
Browser handle type="number" with special processing, I noticed that edge doesn't allow you to type letters in number field.
I would stay with type="number" in your HTML code, type="number" gives you a nice side slider.
- Update HTML form tag onsubmit to onsubmit="testFormCompleteness(); return false", we are using the function testFormCompleteness to match textbook function names.
- Modify the createRecommendation to accept two parameters: acres and months. Rememember testFormCompleteness calls createRecommendation when input data is valid.
- Save and Test (notice error message and how tractor name changes immediately, submit button is deprecated)
- Compare our code with js04.js, notice how are code is more powerful and lot cleaner. However, our code required higher understanding of whats available, knowledge is power.
Web Page Assignment
As done above update js04 to jQuery
H12B Update js05 to jQuery
jQuery js05 Translation:
- Copy js05.html to js05_jQuery.html adn js05.js to js05_jQuery.js
- Update links in js05_jQuery.html and add jQuery CDN (from previous assignment, maintain same CDN)
- Work top down on createLightBox and translate to jQuery jsFiddle
getElementById( lightbox ) beomes $( "#lightbox" ) just sizzile
createElement( "h1" ) become j0.$( "<h1></h1>" )
appendChild becomes just append
.id become either j0.attr( "id", key ) or you can use $( "<h1>", { id : key, "class": "class name" } ); passing create element an associative array - Use associative array when setting more than one attribute, comment out all onclicks
- Make sure you are syntax error free.
- change onload to the standard $(document).ready( createLightbox ); and tests, you should see four images, title, buttons
- Make sure you check inspect console tab no errors, and network tab all files loading
- update showNext function, first element become, last, second by default becomes first
- update JavaScript onclick = function become jQueryObject.click( function )
- JavaScript firstElementChild becomes the method .first - traversing jQuery
- This gets tricky, need to get children and first(), so its
e[ 'lbImages' ].append( e['lbImages'].children().first() )
- update click, test showNext button and save
- update javascript onclick to click, consider making showPrevious anonmous function
- update showPrevious last elment becomes first, prepend instead
- e[ 'lbImages' ].prepend( e[ 'lbImages' ].children().last() );
- update click, test previous button
- for Play button, we us JavaScript timers/intervals, so just set the click function instead of onclick property
- test play button and save
- Update createOverlay,
- set image click function in createLightbox
- most other replacments are the same as above:
createElement( x ) become $(<x>)
appendChild becomes append
new changes:
document.body.appendChild( overlay ); becomes just $("body").append( overlay );
figureBox.append( this.cloneNode() );
overlayCaption.text( $(this).attr( "id" ) )
document.body.removeChild( overlay ); $( "body" ).children().last().remove( );
- Error in webcast if you do an append (you put it end) syou use $("body").childer().last().remove();
if your do $("body").prepend( overlay ) you put it first so you use $("body").children().first().remove();
but since you have the object pointer you can just use $( "#lbOverlay" ).remove(); to remove overlay - Test and save
Web Page assignment
Update js05 to jQuery
H13 Chapter 6 HTML Forms
H13 Permalink and watch Canvas Webcast
Traditional Reading Assignments:
- Gosselin 6th Edition - Chapter 6 Enhancing and Validating Forms
- or JavaScript Definitive Guide Chapter 17 Form and Form Elements
Watch webcast on Canvas.
Introduction to Basic Forms
jsBins are working on edge, on FireFox some of the were going infinite loops
jsBin For the above code, notes:
- right^click open in new window
- clone, disable auto run js,
- you have live preview, can set editor to VIM
- 7th edition datafiles are on canvas, you may complete any 7th edition example in chatper 1 in place of this 6th edition.
Using JavaScript with Forms - Explore Basic Form Document
- Open Chapter06/Chapter/snoot.htm save as snoot1.htm (I also copied over the local files snoot.css and modernizr.custom.65897.js)
- Basic jsBin Example w input type="checkbox" and textarea of snoot.htm
- In Dreamweaver goto Live Preview to test forms
- Standard for checkbox one or more can be right, each one selected independently.
- For tags input, types can be: checkbox, hidden, password, reset, radio, submit, slider, or text
radio only one in group is active/right, password hides text, hidden not displayed to user. - Radio button, required, method="post" jsBin example.
- Delivery Date Analysis select Data HTML jsFiddle or jsBin, my jsBin for this are going into infinite loops.
Improving Form Usability
- Add assistive function, assist the user in entering accurate data.
For example, on Select country, if user selects USA, add drop down for states. - I deleted all default selected options by setting selectedIndex=-1
- Create snoot1.js
- Add comment annotations for @author, @date
- "use strict"; //strict interpretation of syntax
- jsFiddle Code| Analyze jsBin code, note Selected attribute, Use JavaScript to set all selectedIndex to -1, none.
- Add above functions to snoot1.js
- Optional, Add code for listener, IE didn't support addEventListener until IE8
/* run setup function when page finishes loading */ if (window.addEventListener) { window.addEventListener("load",removeSelectDefaults, false); } else if (window.attachEvent) { window.attachEvent("onload",removeSelectDefaults); }
- Add years 2020-2022 to code, can add SELECTED attribute to current year.
- Add <script src="snoot1.js" ></script>
to snoot1.htm at end, and test (F5 reload)
- III) IE7 Support - optional
- Analyze HTML5.0 added whole slew of input types email, month, tel, year, and week (Dreamweaver Insert forms) and also new attributes: required, placeholder, pattern.
- Chrome and Webkit rendering engine are good at new input types. IE11, Firefox 54 lame support.
- IE8 doesn't support placeholder - test page on IE7, can use AOL's, Juno's, or Illuminate's Browser.
- Analyze HTML5.0 again, then add code to snoot1.js remember generatePlaceholder() is part of setupPage.
- IV) Want checkbox checked when user adds custom text.
- Analyze code htmlForms2.htm - get code right^click view page source
- Add code to snoot1.js, adding function autoCheckCustom and add lines to createEventListeners
Test snoot1.htm Selects should be empty, Date should set days by month, TextArea set checkbox on blur.
- Page 390 V) Billing Address same as Delivery Address Option (Usually other way around)
- jsFiddle Code | First Analyze jsbin.com get code
- then add function and code to createEventListeners - test snoot1.htm
Journal Notebook Addenda
- Briefly describe the two form attributes action and method.
- Briefly describe seven type attribute values for tag input?
- Briefly describe the attributes required, placeholder, value, name, and id.
- What are the other two tags besides input for getting user input?
- Will we always have version of IE7 floating around (hint consult webcast)?
Web Page Assignment
- Complete the example in the webcast checklist points roman numerals I..V.
Make sure you test each step as you go along, you may need to use console.log or an IDE that displays error message. Problem with JavaScript a single error can kill an entire page. - As alternative may complete the book example up to page 393 (they are the same).
Checklist:
- Complete Canvas Quiz 6 Forms
- We are skipping chapter 5 quiz.
- Make sure you form assignment is working
H14 Form w Regular Expressions, JavaScript events and Validation
H14 Permalink and watch Canvas Webcast
HTML5 pattern="RegEx"
- The current Regular Expression (REGEX) was set by the Unix GREP command in the 1970s. Since it was a well though out standard, all modern day programming languages support it. Optional tutorial, for this class you need not learn RegEx. Canvas has an sort webcast/video on RegEX.
- HTML5.0 is actually an API not just another XML markup language. As an API it supports the pattern attribute for all form input elements.
- Example enter first name and last name, first letter is upper case for first name all other letters are lower-case. In RegEX [a-z] is a range, lower case letters a to z.
- Modified example, first name and last name, last name also supports these dual upper case DeD DiD McD and accent O'reilly. Note Bene, you should capitalize second word of Di, De (of) and Mc (son of), but not O'name. Oriental names also have hyphen and two upper case, but our RegEX doesn't support this.
- Zip codes example, type=number allows a min and max attribute, but pattern is disabled. Cannot set fixed sizes on input fields put on values.
- JavaScript regexp tester, JavaScript uses '/regexp/option'.method -/ \w+@[a-z]{1,63}\.[a-z]{3}/ \w variable identifier word numbers letters _
The {2} Implies 2 times; {1,63} implies 1 to 63 letters note domain names can have up to 63 letters.
- Advance Age Form Example
- jQuery Form example - jsBin version.
HTML event attributes Important events are focus (had keyboard focus), change (use has changed contents), click (user has clicked element) and load/unload (user has loaded or leaving page). OnSubmit event is generally handled by the submit button.
Importance of Using Existing Standards
With Creative Cloud Adobe dropped Spry Framework, with Spry you had canned validation scripts, but if you wanted to write your own you had to use the Spry syntax, not the standard REGEXP syntax. If you have CS6 Dreamweaver, you add Spry validation by clicking the input item - then the insert->spry Spry Text Field Validation - YouTube - Detailed Description ). jQuery has a standard jQuery validator - you need to add class rules, and adding RegEX is a kludge. Nota bene, both jQuery validator and Spry made the same mistake by not supporting RegEX If a standard exists, it is always prudent to incorporate it.
During it the right way HTML5, added the Pattern attribute. Pattern the value is just a RegEX, this also makes a lot JavaScript validation obsolete. .With Creative Cloud Dreamweaver, implement the extended HTML 5.0 type names, you can view these using insert --> Form, which list then new input tags with the extended form type attribute names. Instead of type="text" we use type="month", etc. the only catch is you still need to implement the pattern to do any validation checks. In some cases, browser will do automatic pattern checking dependent upon the type value. In some cases, the browser will added extra input fields, try the form block out below in various browser, in Chrome Month field gives you a calendar.
In the previous assignment attribute discussion briefly define the dataset tag, and form attributes pattern="REGEXP". You previously defined name, placeholder ,required, title, and type.
Optional HTML Form review - Make sure you understand form basics...
Web-based reading assignments: analyze the first few Chapter 5 Examples or Alternate reading HTML Forms. HTML forms are a basic building block of JavaScript. If you understand HTML forms jump ahead and finish the log file. Else I would re watch chapter 5 and assignment Canvas Web-cast videos. You can also watch these YouTube videos, (once again HTML forms are critical building block in using JavaScript). Don't leave this assignment until you understand HTML forms. You can watch this 25-minute HTML form Video or this shortr fFive Minute YouTube Video.
Journal Notebook Addenda
- Can you figure out how this works
- Do many programming language support regular expressions?
- What do these regular expression symbols mean: ^, $, \d, \s, \w, [0-9], [a-zA-Z], |, ?, . (dot), *, {3,5}. You may want to use this RegEX or short RegEX cheat sheet.
- Also Comment on this very large collection of Regular Expressions.
- Briefly explain these three JavaScript regular expressions...
- /^\d{3}[ -]?\d{2}[ -]?\d{4}/- RegEX Tester
- /^(?!000|666|999)\d{3}[ -]?(?!00)\d{2}[ -]?(?!0000)\d{4}/ Hint and preregister
- /[a-z]{2,}\d*@(saddleback|ivc)\.edu/ and regExpTester
- Briefly define these HTML events: onclick, onsubmit, onfocus, onmouseover
- Mouse Over, what is here happening?
- Can you get an automatic A using the form block below, if not why? To analyze the form block use Web developer menu Forms --> Display Form Details or use right^click inspect.
- What form types are listed below, does chrome provide automatic pattern checking:
Web Page Assignment
Create a web page containg the following form element each one has special RegEX requirements (nota bene examples bove cover the form elements below)::
- first name, (example Upper case Letter), For first name we want one upper cases letter then 1 or more lower case letters. When first name, loses the focus, add a message that says Hello XXX, make sure complete the entire form. Where XXX is name just entered.
- last name, (fancy pattern for last name - Even more fancy jsbin), for last name we will support two capital letters as in Mc, Di and De, and also one accent after first letter O'neil.
- email (pattern="\w+@\w{1,63}\.[a-z]{3}"), email twice, (check two words matching;), For email, you need @ and two word domain. As soon as the second email entry is finished you need to make sure both emails match.
- zip code (zip code & zip code plus 4 example),
- age, For age no one over 140 or under 12 is allowed (this is just type=number min=12, max=140).
- phone number Phone number must be 3 digit area code, then 7 digit phone number. RegEX: \d{3}[ -]?\d{3}[ -]?\d{4}, modify the previous regex to make 1 before area code as optional.
- User-selection element full-time, part-time or full-time student, you can use either a radio button group or drop down selection box.
Checklist
- Review you journal notebook you have 51 entries.
- Make sure you understand HTML 5.0 placeholder, required and pattern attribute.
- Make sure you have completed the chapter 6 quiz.
H15 jQuery version and HTML Forms Browser Based Validation
H15 Permalink and watch Canvas Webcast
Customized Browser Based Validation
- HTML5 added input types usually have automatic data type validation -
- On previous example try entering text for zip/phone number and also try submitting blank document noticed required attribute.
For HTML5 only required attribute name is needed, but for XML is always name value pair required="required" - Test your current snoot1.htm notice it loads results.htm - most of the time we send data to server for processing aka formData.php.
- Best practice minimize user input friction, not want user to enter same data twice on error, or make it difficult to enter data.
- You don't need to have pages 404 and Up as part of your assignment - just follow my next two examples.
- Example - analyze form...
- attributes novalidate stops default browser validation;
- onsubmit="javascript code;" executes confirm window before calling the action return true continues processing
- event.preventDefault() prevents the default form action to occur
- Way author has written this example, especially his validation is not good, my example is better.
- In general with validation use HTML5 API as much as possible, i.e., Pattern, Required, minimize form Validation w onsubmit and onblur.
- formValidity.htm
- Validate that both passwords match page 425
- Validate credit card number and credit name selected.
- Later on Validate credit card number relative to credit card selected.
- Modify snoot1.htm form block with onsubmit
- Modify snoot1.js with new JavaScript code.
jQuery - Best Practice Version
- Save snoot1.htm as snoot1jQuery.htm, save snoot1.js as snoot1jQuery.js.
- Add jQuery CDN <script src="https://code.jquery.com/jquery-3.6.0-min.js"></script> and also update src link at </body>
- Use HTML5.0 API take advantage of Pattern and Required attribute.
Toss up consider using HTML5.0 placeholder attribute and specific types month, number, zip, email, etc.
Pair specific types with pattern e.g., type="zip" pattern="\d{5}[- ]?\d{4}"
In general, w HTML5.0 specific types have browser based patterns, validation will flag whenever you mix a specific type like "zip" with a pattern.
Chrome and Webkit rendering engine are good at new input types. IE11, Firefox 54 lame support. - Browser Usage -
Support Table - just because it is supported doesn't mean it displays well, not type w pattern may not gain anything on Firefox.
QA and test engineers matter. Will mix new types w pattern and test in Webkit (DW internal) and Firefox.
- Cleanup HTML code, in HTML get rid of both long option month, day, year and state. Will be writing JavaScript code to do this.
- Cleanup JavaScript code, author's version of updateDays, setupDates stinks. jsbin Example, or jsFiddle Example. Will use jQuery append to populate all Month, Day and Year.
Remember in good code design if you do something twice it should be a function. Instead of repeating months each time as long options chains we will have a single array of months and use JavaScript to populate all options in both month drop down list boxes. For Day and Year we can use a simple array iteration. - Make sure you simplify HTML code after JavaScript code cleanup.
- Make states an array, use .each chain method for copying values, and setting all select statements, jsBin Example. | jsFiddle Example
- Translate document.getX to jQuery Sizzle selectors
- Move all createEventListeners and setupPage to Standard $(document).ready( handler...
- Remove IE7 support, note we are using jQuery 1.12.4 last version to support IE6 and 7. Later jQuery versions dropped IE8 and before support.
- JavaScript .style property become .css chained method, can set two properties argument 1 is CSS class name, 2 is property value, or use array map.
- Can leave zeroPlaceHolder, generatePlaceHolder and checkPlaceHolder() along.
- Bonus set date, to two after current date, except for Friday which is three days in the future. You may want to set the dates as Amazon does, give the user three options for delivery. Set default location using HTML 5.0 API geolocation
- Add customized browser based validation to your H13 assignment
- Implement a jQuery version of H15.
Checklist:
Make sure you have completed Canvas Quiz 6 Forms
Also check your current
Canvas quiz grades
H16 Future Expansion
WIP
Will add RWD chapter or slider.js or react.js iif time permits.J1 Chapter 12 Introduction to jQuery
J1 Permalink and watch Canvas Webcast
Traditional reading assignment:
- Read Chapter 12 Introduction to jQuery
Implementing jQuery
- Setup jQuery CDN link
- open Chapter12/Chapter/rocks.htm save as rocks1.htm
- Create a valid HTML5.0 starting point. Find replace ' with " also change device to viewport only
- Book is using a local jquery-1.11.1.js, we will be using a jquery-3.7.1.min.js CDN.
CDN can provide better download performance and once you download a specific jQuery it will be part of you JIT cache.
Add jQuery minified CDN link to rocks1.htm before </body>
Minified whitespace have been eliminated and shorter variable names.
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>jQuery UI 1.13 supports 3.6 so will used latest supported jQuery.
- Make sub-menus visible using ul and class selectors
- Analyze HTML notice nav tag with ul/li tags. Notice the descendent's of ul.mainmenu, and the ul children.
- Create script1.js add author and date comments
- Make sub menus visible for cruises, rates & directions visible always for now, note class .show has CSS display:block
$("ul.mainmenu li").children("ul").addClass("show");
- Add event listeners so sub menus only show on
hover,
- jsBin example using .hover( mouseenter, mouseleave );
- Add code to script1.js make sub menus only visible on mouse over.
- Need to be specific per menu item, pass event and use event.currentTarget
- Page 826.add event argument to display/hide and/or to your anonymous function. add just hide,show()
- Page 827 Animation, experiment with slideDown() instead of show()
Journal Notebook Addenda
- What is the difference between the object jQuery and $?
- List and describe three jQuery methods used to traverse the DOM. - jQuery API.
- List and describe three jQuery DOM manipulation methods - ECMA6/7 have same methods as jQuery.
- List and describe two jQuery animation methods. - jQuery API Effects
- Class was using jQuery 1.12.4 because it was supported by jQuery UI 1.12, But jQuery UI 1.13 is supported jQuery 3.6.1 Why was jQuery 2.x skipped over?
- Compare and contrast methods: addClass(), show(), and css( "display","block")?
Web Page Assignments
- Complete the books rocks1.htm example.
- Complete textbooks page 834-836 Hands-on-project 12-2
Checklist:
- refer to syllabi's grading criteria and count how many assignments you currently have and need.
- check Canvas quiz grades make sure you have taken Chapter 12 quiz
- make sure you home page links to all your assignments and your Journal notebook
J2 Intro to jQuery - jQuery Tag/ID Selectors & JavaScript onclick event review
J2 Permalink and watch Canvas Webcast
Prerequisites basic knowledge of JavaScript assignments h0..h8.
Optional Online reading assignment:
- PDF sample Pages from: Quickstart jQuery and JQuery UI, VisualGuide by
Jay Blanchard, Valore has book for less than $10, not that impressed w book.
- Will review Class Notes during webcasts its a good review, will expand on minify, libz and compiler closure.
- or Sam Teach Yourself JavaScript, hour 19-21;
- Amazon does have some 4 start jQuery UI books.
jQuery chaining and CSS method
With the use of chaining you can apply a method to the selected HTML DOM element. The method css, will set the CSS for the selected element.
jQuery API - css Methods, This method is relatively easy, you select the element, then use element.css( cssPropertyName, Property value). You can pass multiple values using JavaScript property key, value pairs Read answer 162, (or property name : property value ); element.css( { "name":"value", "name":"value" } ), note css Method inappropriately refers to it as a map.
Summary: jQuery adds a single jQuery object identified by the $, it has one DOM selector argument. The selector argument is either JavaScript object (e.g., document event, this ) or a CSS3 selector string. For example...
- $( "css selector").method. css Selector: tag, #id .class, or CSS3 functions
- jsFiddle Basic Color Example
- More advance jsBin with Toggle function.
- Can Click the CSS Strings:
- $( "#jQuerySelectors strong" ).css( { "color":"lime", "background-color":"black" } ); //invert assignment
//Space is descendant, looking for a inside of #jQuerySelectors - $( "#jQuerySelectors a" ).css( { "color":"orange", "background-color":"black" } );
- //CSS3 DOM selectors pseudo classes nth-child(),
//note space descendant children, grand children, ...
// > selects only children can use space or > here
$( "#jQuerySelectors ol>li:nth-child(odd)" ).css( "background-color", "lime" ); //odd span tags in this assignment
-
//CSS3 DOM selectors pseudo classes
$( "#jQuerySelectors ol>li:nth-child(even)" ).css( "background-color", "skyblue" ); //odd span tags in this assignment - $("#jQuerySelectors .webBasedReading" ).css( {"font-size":"larger", "border":"2px solid blue" } );
Click here or F5 to reload page, F5 should reset the above changes
- $( "#jQuerySelectors strong" ).css( { "color":"lime", "background-color":"black" } ); //invert assignment
- jsBin of above examples.
Optional Web-based reading assignment:
What is jQuery, Wikipedia intro, specific W3C selectors, consider adding the plug-in Wappalyzer or Alexa; Read through installing jQuery and minify. Read through jQuery Intro stop before jQuery Events. Read about selector engine sizzle - how jQuery selects elements. Take a look at this jQuery testing site, it uses jsLint.
Journal Notebook Addenda
- What is the difference between the jQuery DOM manipulation methods prepend and append.
- Using jQuery sizzle how would you select the first and last paragraph element on a page.
- What is minify, and closure compiling?
- Should you download and use a local copy of jQuery or use a CDN (list advantage of CDN)?
Web Page Assignment
- Complete this selectorTableEasy.html web page, corresponding jsFiddle. and jsBin
J3 (formerly H12) Intro to jQuery - jQuery Selectors & JavaScript onclick event review
J3 Permalink and watch Canvas Webcast
Learning Objectives: Introduce CDNs, jQuery Object and CSS method, go in depth on jQuery Selectors, review of JavaScript functions and jsFiddle.
Reading Assignments:
- Chapter 1 Notes Visual Start jQuery - we are only covering the introduction and chapter 1.
jQuery and JQuery UI, Visual Quickstart Guide by Jay Blanchard, Publisher: Peachpit Press; 1 edition (December 13, 2012), ISBN-10: 0321885147 PDFsample Pages. - Introduction Class Notes. - Valore has book for less than $10, can get international version.
Notebook Addenda:
- Comment on Stack-flow discussion minify versus gzip?
Note some developers also use code obfuscators: http://javascriptobfuscator.com/
Web Page Assignment:
- Complete this jQuery Selector assignment Table, it uses the JavaScript file: selectorTable.js, The table also connects to a jQuery CDN.
- You can use jsFiddle below for help, (make sure you have your JavaScript Console window is open, to do this click the third leftmost icon of the Web Developer add on or use right^click inspect element console). Each jsFiddle has completed some of the assignment table. All four jsFiddles are already built into the assignment table.
Nota Bene, in jsFiddle we need to set all function names to variables, so we use myInvert = function( str ), not myIvert( str ). - jsFiddle1 - of entire assignment,
- jsFiddle2, specifically for testing span selection
- Pseudo JavaScript jsFiddle3 functions.
- jsFiddle4, simplified table for testing table selectors
Live Examples:
- jQuery selector examples
- W3C jQuery Selector Test (can paste your Web Page test area, to get selectors working)
- jQuery examples setting CSS using element.css( "cssPropertyName":"cssPropertyValue" );
Checklist:
- Make sure all JavaScript core assignments are done (i.e, h0..h8).
- Make sure all Canvas quizzes are done, click the my grades button on Canvas.
J4 (formerly H13) jQuery Methods and Events
J4 Permalink and watch Canvas Webcast
Leaning Objectives: Introduce events, anonymous callback functions, and review selectors.
Reading: jQuery API Events and W3Schools jQuery Events
Look over the 20 useful jQuery methods;
More Specific jQuery samples:
- html method, set html content of element
- Page selector and onLoad/Ready example
- ID Selector with ready event. - as soon as page is loaded the ready event handler is called
- Event Click on p tag (note don't need the ready event first)
- Event mouseenter on p tags
- jQuery $(document).ready( event Handler )
Web page assignment
Complete eventTable.html , it it uses the files: eventTable.js, eventTableDaylight.css, eventTableMidnight.css, and eventTableTwilight.css.
Assignment has several jsFiddle built into eventTable.html , some of the jsFiddles complete additional parts of assignment.
Journal Notebook Addenda:
J5 (formerly H14) jQuery UI and jQuery Plug-ins
J5 Permalink and watch Canvas Webcast
Web-based Reading Assignment:
If you have prior experience with Dreamweaver (DW). Creative cloud 1017 and up Dreamweaver has access to both bootstrap and jQuery. To access jQuery Select Insert --> jQuery x, the current creative cloud has three new categories: Bootstrap Components, jQuery Mobile and jQuery UI. With DW simply drag and dropping various jQuery UI components. DW creates a local version of jQuery and jQuery UI. CC 2017 and up is currently integrating jQuery UI legacy 1.11.1.
General introduction read the first page of jQuery UI API. We don't need jsBin, the jQuery UI API has good examples and an excellent interactive demo section. In general jQuery UI is very extensive, but it can divide it up into the following categories:
- Effects -specific effects such as blind effect - good effects demo page.
CSS3 has animation but its a pain to implement.
- Core Effects - core methods used in the effects category toggle
- Interactions - drag, sort or resize widgets, note HTML5 and CSS3 have deprecated many of these.
- Widgets - datapicker is nice but type='date' works well in chrome, slider HTML5.0 - comparison file.
Demos menu, - tooltip (note you vary arguments w side example) - tabs - dialog (customizable confirm)
My favorite accordion this assignment page, Menu Widget office hours, tabs, tooltips is nice but hitting incompatibilities
- ThemeRoller (this assignment page selects a new UI theme based on the student design) - use new design to change theme.
- Icons - DW will let you complete class names once you set the CSS link, I prefer HTML entities. Once in DW using code view just pause after the & (note & is an HTML entity &).
Web Page Assignment
Complete jQueryUI.htm Web page. I'm using the le-frog theme-roller, you should use a different theme roller (click gallery tab), the links to the foller are in the CDN file jQueryUI.htm,. Corresponding jsFiddle (not working probably older version of jQueryUI) - jsBin version (jsBin loaded jQuery 3.1 w jQuery UI 1.12).
Notebook Addenda:
- List and briefly describe three new jQuery UI effects that standard jQuery doesn't have.
Basic jQuery effects are slide, fade and animate either slideUp, slideDown and slideToggle.
- Which language is the theme roller written in and why?
- Why did I not use a code playground for the examples under web based reading assignments.
- Whats wrong with jQuery Tools - accordion example, github may help. - can compare with jQuery UI github.
J6 not updated to just XML/jQuery yet snapShot Introduction to XML and Image Viewers
J6 Permalink and watch Canvas Webcast
Learning Objectives:
- Become familiar with XML (XML is everywhere, HTML5, Microsoft Office, Open Office, etc)
- Understand basic types of image viewers
- Create an XML file that interfaces to snapShot
Reading: Attend class and/or watch the snapShot Canvas Web-cast, review the snapShot Web Page, try out different image viewers.
Log File Addendum: What is pixastic? Note snapShot currently does minimum Image processing however I should write additional ImageMagick or GD filters. Why should I use GD/ImageMagick instead of pixastic?
What is xmllint, and JSlint (too picky). The snapShot validator is using xmllint to validate an XML file. How is this snapshot generated? What are Kernow , Saxon and DTDGenerator? On CIM I'm using xsltproc.
Which Java Script frameworks does the original lightbox use. What input format do these Flash Viewers use and why?
What input format does snapShot use? How does each snapShot image viewer know which XML file to read (hint URL encode variable)?
Analyze snapshot definition (DTD), (note * in a DTD is a regular expression symbol) and use disney.xml for help. Look at a XSD (XML Schema) for snapShot.xsd, Note this format uses an XML specification (DTD) to define the DTD of snap shot files. When you display XML in a browser,
the ending tag is dropped and replaced with /> instead of </file>. Also just like
with HTML the header lines are not displayed. A default header for a snapShot input configuration file is....
<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type='text/xsl' href='https://cim.saddleback.edu/~tdedonno/snapShots/xsl/flowLayout1.xsl' ?> <!DOCTYPE files SYSTEM "https://cim.saddleback.edu/~tdedonno/snapShots/config.dtd" >
The second line style-sheet is optional, you can use either CSS or XSLT to render an XML document, (Nota Bene HTML5 is XML based.). XSL transformation sometimes require the help of an XSLTProcessor, snapShot has this capability. Note XSL quickly became XSLT which is super charged CSS and transformation language. You can apply CSS to XML nodes, id and classes the exact same way we apply CSS to a XHTML document.
Note XSD is a lot more complicated than DTD, but meets a XML Schema definition. With XSD we usually specify the XSD file, with the root node,
(i.e., <files> for snapShot), a typical config file would look like...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE files PUBLIC "-//tdedonno//cim snapshot//EN" "https://cim.saddleback.edu/~tdedonno/snapShots/config/config.dtd" >
<?xml-stylesheet type='text/xsl' href='https://cim.saddleback.edu/~tdedonno/snapShots/xsl/flowLayout1.xsl' ?> <!-- may be best to leave out XSL if you want to view the XML Contents as nodes -->
<files
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:noNamespaceSchemaLocation='https://cim.saddleback.edu/~tdedonno/snapShots/config/config.xsd'
large="Absolute URL to the large folder" medium="absolute url" small="absolute url">
<file icon="image Location Relative large,medium and small folders" author=""
press="" rollOver="" useAuthor="false"></file>
....
</files> You must use absolute URL (aka full path with server) for your small, medium and large attributes values
Web Page Assignment: Pick one or more of the Java Script viewers on snapShot (jquery, lightbox, or spry), Create a local XML file that points
to your local image set. Make sure it passes the snapshot (DTD) using snapShot validator.
This assignment is easy even Minnie Mouse has done it twice, first on her home page at the bottom and
then on this stand alone page.
For stand alone page, Minnie Mouse has an XML configuration file, XML has passed DTD validation and a sample viewer. But she some of her images are not working and she has only one image size folder,you should have three separate folders: thumbnail small images (60x60), medium images (200x200) and large images 640x480 or larger. However, Minnie is kind enough to give you the following tips:
- Create or get a set of images, System supports three image sizes, both Fireworks or Photoshop can batch auto scale images. Canvas snapShot web-cast should demonstrate how to batch images using Fireworks.
- Create a config XML file make sure if passes the snapshot (DTD), Minnies does using both CIM Validator and also W3C engine.
- The location of your images must have a full CIM path, aka /~mmouse0/images/minnie.jpg worked for me.
- The config variable values must be a absolute Web address, aka https://cim.saddleback.edu/~mmouse0/images/config.xml
- You may want to add extra
tags and mistakes and see what happens with validator. Remember a well-formed document passes XML syntax verification, a valid document meets its DTD.
For XML 1.0 files the first line has to be....
<?xml version="1.0" encoding="ISO-8859-1"?>
- Please note both CIM Validator and also W3C engine., notice the variable config=value and uri=value, these values are generally URL encoded. With URL encode special characters are translated to a URL code. For this assignment you don't have to create an URLencode. But you should be aware of them, for example, if config=http://ab c/ the URL encode is config=http%3A%2F%2Fab%20c%2F%0A, Meyer's site has an URL encoder/decoder.
- Determine the URL of the JavaScript viewer you will be using, Minnie is using lightbox, just set the config to your configuration file.
- Set the URL config variable to the absolute path of your snapShot XML file.
- To integrate snapShot into a Web page you can investigate using an iframe.
- Make sure your cimw160 home page, has a link to your completed assignment.
Extra Credit: Find a JavaScript viewer that is currently not implemented on snapShot and add it to the system. Make sure the image viewer uses an XML configuration file, then just modify its input so that it works with the current Snapshot DTD. If the program doesn't use an XML configuration file, you will have to write a PHP file that converts snapshot DTD to its required DHTML format, I had to do this with nivoslider (check the DHTML generated output).
Extra Credit: Write a GettyImages.com or a Nasa Image API or an interior National Oceanic and Atmospheric Administration API interface to snapShot. I did this with flickr. This is relatively straightforward. First you need to find the flickr API. All major sites have a corresponding API, which allows a Web Programmer to extract XML or JSON based data, NOAA has good API documentation. Using the flickr API.I, I created a routine to extract flickr XML data, then using XSLT, I translated the the flickr XML format to the snapshot (DTD) XML format. You can also considering do this with some other picture site.
Checklist:
- Make sure h11 is done. Considering putting it inside of an IFRAME within a Web page..
Ajax1 Introduction to Ajax, Basic Read & Traverse XML Data
Ajax1 Permalink and watch Canvas Webcast
Nota Bene,
Assignment description has renamed xmlDOC to countriesData, but 12/2021 video is using xmlDOC. The console window is auto completing xmlDOC to xmlDocument, so you can no longer use the variable name xmlDOC. Plan to create a new webcast 12/11/2024
Reading Assignment
- Gosselin 6th Edition Chapter 11 AJAX
- Web Warrior 7th Edition Chapter 11 AJAX and Fetch.
- Quiz for Chapter 11 is Extra Credit
Ajax Basics
- AJAX: Asynchronous JavaScript and XML, but data sent can be JavaScript code, XML or JSON.
- In general we use the browsers built-in XMLHttpRequest (XHR) object to request additional data from server, and the use JavaScript "eval" and HTML DOM to display data.
- Goal: Update part of web page without rewriting the entire page. It is very inefficient to go back to server if we only need a little more information.
Ajax in Action Samples:
The student search page, was written before jQuery. When you type in the dialog search box, it does an AJAX call to the file search.php which searches a student database on cim, returning the first 10 matches. In your browser, use right^click inspect network, and noticed that JavaScript is sending a request to the file search.php?q=a;, In network window, click that file and look for response to the right. You will see it creates an array with a call showQueryDiv. The PHP program search.php searches the database and creates a JavaScript script with showQueryDiv function call. The original program does an eval on the response from search.php, which displays the first 10 matches beneath the input dialog panel. Search.php returns JavaScript, rather than passing JSON or XML back and forth. Both JSON and jQuery became popular several years after program was written.
Google suggest search has a similar mechanism it searches a database of all search requst and also list your your current request. Google search also uses a program called search which returns JSON. Notice the response in inspect --> Network and the popup dialog panel beneath the input box. If your are reading this during trading hours (6AM-1PM PST) - goto a financial site and notice how AJAX is used to maintain real time quotes.
In the samples above the servers, are providing a Web Services. Web services provide data upon an XMLHttpRequest. On cim search.php is a web services which searchs the student database.
Ajax Examples
- JavaScript version of countriesEasy.html note you can access jStudent's countriesFinal.xml Files from cim.saddleback.edu, but locally its best to have it in the same folder.
- Use right^click Inspect Network, and notice the XML loaded as a response from AJAX call to countryFinal.xml
Web Pages Assignment Translate countriesEasy.html to jQuery.
- rename countriesEasy.html to countriesEasyjQuery.html.
- Modify console.log with a counter, first console.log output is 1 with comment, then 2 with comment, etc. this makes it much easier to detect where a script is failing.
- Add standard cdn <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
Remember on cim all requests are https. Use Inspect to make sure jQuery is being loaded. - Save a local copy or countriesFinal.xml, right^click save. Both cim.saddleback.edu and www.saddleback.edu for security purposes are on a DMZ and prohibit CORS (Cross Origin Request Sharing). A server or a server's folder/file needs to allow CORS, in order for a program on another server to access its data when using an Ajax XMLHttpRequest.
- Update all getX to $('sizzle Selector'); Attributes access becomes chained event .attr( "name" ), - Use this jsBin example, to update newCountry function, use name as the search/find not code. The jsBin is using a drop down list box with code, we have one with country names.
- Test to make sure div blocks with id name and quickFacts is updated after a country is selected in the drop down list box.
- The AJAX code at the docuement top will be replaced with a jQuery $.ajax call. jQuery has two short-cut AJAX calls $.post and $.get( url, function(data, status) { ...} ); where data is URL response. But we will be using $.ajax() call instead.
- You can load XML documents from a different site but this can cause CORS request problems which we will be skipping, make sure you have countriesFinal.xml. in the same folder as your countriesEasyjQuery.html. Nota Bene, all jsBin has the code built in as an xmlDOC string. We set the AJAX response to the memory string xmlDOC.
- Make sure you drop down list box is being populated. jQuery AJAX version - not available but in webcasts populates list box and has chaining on the AJAX object., not it sets the vairable xmlDOC;
Analyze this code, then add it to the end of your document, delete all the original JavaScript AJAX code in the header, you should just have this AJAX code and newCountry in your countriesEasyjQuery.html
- Ajax calls can become long associative array $.ajax( { url: "urlString", success : function( result, status, xhr ){ ... } , error: function( result, status, xhr ) { ... } } );
- Alternative to long associative array is to use chaining, line in jQuery AJAX version - not available but in webcast.
- result is the resulting data from the ajax call; status is status of the call 200 okay; xhr is XMLHTTPRequest object, it contains status and the ajax response.
- About number in AJAX3 has detailed AJAX examples.
-
Best Practices
- When using Array maps, and anonymous functions, write just a little code at a time one missing parenthesis or brace can ruin your whole day.
- Remember in a scripting language like JavaScirpt you can test all code in console window one line at a time.
- Remember Ajax is asynchronous so its best to set all data in the success function. Remember XML data may or may not be available when you execute another method.
- You also have an option error:function( result, status, xhr) which is good to implement.
- This jsBin has newCountry function, modify program to use name, and add the two div blocks id name, and id quickFacts.
Web Page Assignments
- Complete a jQuery version of countriesEasy.html, - follow steps 1..12 above in translate to jQuery.
Notebook Addenda
- How do you use a browser to view and identify an Ajax call and its response?
- List and describe three basic options url, success and error of $.ajax?
- What is an XMLHttpRequest?
- Why do we use Ajax? (especially w smartphones)
Checklist:
- If you did this assignment make sure you take the Ajax Extra Credit quiz.
- Assignments ajax2 and ajax3 should be a lot easier after completing this assignment
Ajax2 Add two more XML files to Ajax1
Examples
- If you ran into troubles in AJAX1, just use countriesEasyOptions.html (aka. jQuery AJAX version.), add this jsBin for newCountry function, modify the code to use attribute name instead of attribute code, and add the two div blocks id name, and id quickFacts.
- When the user selects United States add a states drop down menu. You will need add an AJAX call to states.xml.
- This jsBin will set state select box when US code is selected.
- You just need to add the 2nd Ajax calls to states.xml to set xmlStates.
- To just load an XML file one just needs:
$.ajax( { url:"states.xml", success:function( result ) { dataStates = result; /*can add parseXML */ } } );
Best practice set the data as soon as it is read, don't rely on a function later on that assumes dataStates is set. Remember this is an asynchronous event handler.
- However, in this case you can just set the states select box options, you don't need to save the xml states file.
$.ajax( { url:"states.xml", success:function( result ) { $( result ).find( "state").each( ... refer to previous jsBin ); } );
- This file currencies.html illustrates using basic console commands on currencies.xml, All the commands you need to add currency.xml to your AJAX1 assigment are in the file currencies.html.
- AboutNumber has more advance AJAX examples.
Web Page Assignment
- Add both currency.xml and states.xml to your jQuery countries.html file created in AJAX1.
- Add a div blook with currencyFacts, and a drop down list box with states when United States is selected.
Notebook Addenda
- In the previous console test file currencies.html, what does the jxhr return value of $.ajax represent.
- If jQuery is not available after making a CDN call, what two things should you do?
Bonus
- Add flag images, using flagcdn.com, it is not that hard, they use the two country codoe letters. For example, Brazils 2 letter code is br, so the flag is just https://flagcdn.com/br.svg.
- Add Time Zones, by using an eval with the country name.
- Add a call to either the National Weather Service API or weather channel API mashup or Google's secret Weather API. These API may not work on countries only cities/state, but note you do have cities and Longitude/Latitude. You can use darksky api.
- Complete books Ajax example they are using darksky api.
Ajax3 (Worth 2 homework points) Create a Mash-up using XML Data Sources, Ajax and BOM
Ajax3 Permalink and watch Canvas Webcast
Not updated, but you can use the jQuery file you created in Ajax1, you will need to add additional div blocks, and fill these div blocks with content from other sites, content is dependent on country selection. By completing Ajax1 first this
Traditional Reading Assignment:
- Gosselin 6th Edition Chapter 6 DOM and Chapter 11 Ajax
Optional Web-based reading assignment:
BOM, DOM, GetElement Examples, Watch Canvas assignment Web-cast. Difference between DOM and BOM. Style Example.
Java Script has no forward referencing, therefore you cannot access a Web Page element in Java Script until you have processed (or read) it. For navigator, a DOM structure already read JavaScript supplies the following document methods: getElementById (standard), getElementsByClassName(), and getElementsByTagName(). Note both ClassName and TagName return an array of objects, an single element would be an array of size one. Note with jQuery, the sizzle selector engines does all DOM selection using the three basic JavaScript document method calls.
Notice Google Geocode has to be opened in a new page (note you get blank page in Geocode current iframe).
Use Inspect element, look at the DOM tab, analyze the document object, notice it follows standard DOM/XML model.
To get data one would look for a MySQL Database, or a XML/JSON file, (e.g., World Bank) or a Web Services Feed (e.g., Google Geocode). A database has a fixed schema (format), it is very good for server side access and when you are dealing with fixed number of fields. In many situations a Web Services will access a database and return an XML stream. XML is ideal for small to medium size flexible data sources. For example the countriesFinal.xml file is medium size file with missing fields for many entries, (some entries have city and language others don't. For example the DTD line country (city | language)*, implies each country node can have zero or more city and/or language children. Also, one would use an XML file, when they need to use the entire data set each time (e.g., creating the country select box in countries.html). If you are only making calls to get random data occasionally, you would use a Web Service (aka stock quotes) or maybe to map from a ISO country code to a latitude/longitude. I decided to add latitude, longitude and ISO codes to our original countries.xml file. XML Reference Book includes full descriptions of Java DOM, SAX, XSLT, XSD, DTD and XPATH. In assignment H11, we will discuss XML and related XML technologies in more detail.
Log File Addendum:
- What is a rendering engine (aka Web Browser Engine)?
- Can one change the rendering (CSS styles) after a Web Page has been rendered, if yes how (hint)/and assignment on j2 events?
- What is this World Bank and Google Geocode Returning?
- What are the three basic Java Script object Window dialog panels (Hint look under JavaScript Window object for alert box and two basic input dialog panels)?
- Basic html element example, changed by getElementById documentation
- Examples DOM GetElementById in a form
- JavaScript window object - represent BOM, document is a subset of DOM, H1 Tag illustrates reading DOM and setting window.alert
- Intro to XML DOM Traversal, more specific getElementsByTagName using JavaScript get Function on a XML DOM Object containing the data books.xml.
Web Page assignment: Given countries.html, it uses this DTD, and this XML file ( you may be able to link to /~jstudent0/map/countriesFinal.xml ). You need to finish countries.html, snapshot image of final assignment (including Weather extra credit Mashup). To finish countries.html, follow these step...
- Download and analyze the countries.html During analysis how does countries.html use countriesFinal.xml. and how does countriesFinal.dtd relate to countriesFinal.xml. P.S.You will have to download both files or link to countriesFinal.xml.
- For debugging purpose call to update Wikipedia iframe is commented out, uncomment your final version.
- In order to used Google Maps from your home folder, you need to get a Google API Key. Instead of a Google API key you can implement HTML 5.0 Geolocation but its so slooow, see item 9.
- Add correct latitude and longitude to the Google's Map API call. For both 3 and 4 you will need to traverse the XMLDoc object (countryTags is already defined). Live view Example for traversing a XML DOM document, the documentElement is entire document; childNodes are the children (html tag has two childNodes head and body), nodeName is tag name, and nodeValue value between the tags. For this example you need to look for nodeNames city and language. Language has both an attribute and nodeValue, city has two children nodes name and population.
- Print out all the Quick Facts for the selected country, at present only country name is printed.
- Add a set of GUI elements next to the select box (in the controlPanel) to set the color, background-color, font-size, and font-family of quickFacts. You do this by simpling getting the element for the controlPanel and setting its style object. To modify the CSS style presentation, in a document JavaScript first gets then HTML element, using the HTML element Object followed by the style property with Camel case CSS style name: Font Color, Set background Color and
, what happens?
- When the user selects United States, add a select box of type states. You do this by creating the select box, read in a states.xml file, set the contents of the box. But make sure its visibility is hidden. When the user selects United States, just set the select box to visible. You could add state long/lat, they also have ISO state codes.
- For Extra Credit, add another div block that makes a call similar to the Wikipedia such as a call to the National Weather Service API or weather channel API mashup or Google's secret Weather API. These API may not work on countries only cities/state, but note you do have cities and Longitude/Latitude.
- You can also considering adding a button get Current Location. This is done using Geolocation, an HTML 5.0 Geolocation API - This site has a good set of examples
Checklist:
- Complete Canvas Quiz 5 BOM/DOM.
- All quizzes on Canvas (except jQuery) should be completed, use Canvas quiz grade to verify this.
- Make sure assignments h0..h11 are on your home page.
Ajax4 (Worth 2 homework points) jQuery Ajax/DOM & Unit Testing
Ajax4 Permalink and watch Canvas Webcast
Reading: Ajax -Asynchronous JavaScript and XML. - CIM Student Search and Google Suggest -
check out the Ajax response against the pop up list box using FireBug net tab, on the net tab check out the GET request and the response.
All browsers have an XMLHTTPRequestObject, on a standard HTTP request a new page is sent, on an XMLHTTPRequest, we put only data.
Browser XMLHttpRequest Object Has Methods:
- open( "[GET | POST]", URL [, async ] [, username] [, password] ); Opens a Connection to the URL
- send( [ data ] ); sends the URL to the Connection specified by open, the data can be a javaScript map or URLEncode format "Number=3";
XMLHttpRequestObject Has Properties:
- readyState one of four values UNSENT, OPENED, LOADING or DONE, which equal 1,2,3 and 4 respectively
- responseXML HTTP status 200 Okay; 404 Not Found;
Has Events
- onReadyStateChange
- Example - XMLHttpRequest
jQuery AJAX Methods.
- ajax([javascript map] ); can specify URL, data, datatype and callback functions.
For example: $.ajax({url:"demo_test.txt",success:function(result){ $("#div1").html(result); }
Load the contents of the file demo_test.txt into the id #div1 - jQuery AJAX example Table for AboutNumbers.
- You can also chain methods to the $.ajax
- Note load, put, get and getScript are ajax short-hands, load( url [, data] [, success ] ) load HTML data
- get( url [,data ] [, success ] ) - URL string, data is map or string sent to server, success is function to call on success
get( url, "number=3", showMessage ); or map { number:3 } - getScript( url [,success callback] ) get and evaluate a JavaScript - jQuery shorthand $.ajax( { url: url, dataType: "script", success:success } );
jQuery traversing and other helper methods
- $.each( collection, callback ) Collection is an object or an array, we call function callback on each enumeration
- DOM traversal - all XML documents are trees with a root node and children/siblings. In HTML the root is <html lang="en"> the first two children are <head> and <body>; <head> and <body> are siblings.
Log File addendum: Document the jQuery AJAX method by documenting seven JavaScript map arguments.
Web Page assignment: Create a Web page that allows the user to enter a number, your JavaScript program should output information about the number. You have to make an AJAX call to Minnie mouse's XML about number, her file will tell you if your number isGermainPrime, isFermatPrime (all Fermat numbers are prime) and isFibonacci. You also have create a JavaScript file with five more number sequence tests. You may not hard code the numbers into your program, you must have an isFunction, that returns true or false. Load you JavaScript file using $.getScript, do not use a script tag with a src attribute. You can also use the standard jQuery AJAX w contentType: "Script" and use an eval in the success function. Your five number sequence types can be chosen from....
- Triangular Number t = { n( n+1) } / 2 where n = 1,2,3... refer to the isFermat script for help.
- Pentagonal Number p = { ( 3n 2 -n ) } / 2 where n = 1,2,3... refer to the isFermat script for help.
- Perfect Square, 25 is a perfect square 5*5 = 25
- Prime - divisible by only 1 and itself - write your own isPrime function, don't cut and paste Minnie's code.
- isEven - you man want to try out bitwise operators, Minnie has special code for isDivisibleByThree.
- isOdd
- isDivisibleBy5
- isMultipleOfTen
- Palindrome - reads the same backward as forward (e.g. 101, 121)
- Mersennie Prime ( 2P - 1) Nota Bene Gremain is 2*n +1 )
- Palindromic Prime
- Triangular Prime
- Prime Pairs (5 & 7, 11 & 13 )
- Two sites with lots of sequences: OEIS Search - Project Euler - you may pick your favorite sequence.
You must validate correction execution of your JavaScript number sequence file using unit testing; Goofy did this for Minnie Mouse. Goofy also wrote a file that uses CSS and AJAX to display AboutNumber XML output.
Nota Bene, we are not supporting CORS (Cross OriginResource Sharing), so you have to run all tests using the CIM server, or if you have XAMPP, you can test everything locally. If you can get your .htaccess file working on cim, I will give you bonus points.
Details on Minnie Mouse's Assignment....
Once again Minnie Mouse has started this assignment so it is not that hard. In addition, Minnie Mouse gives you access to an file that tests for Germain Primes and Fermat numbers. You simply send the request https://cim.saddleback.edu/~mmouse0/aboutNumber/aboutNumber.php?number=17 where number is the number you want to test, output is in the aboutNumber.xsd. schema. Minnie has the following files:
- aboutNumber.html (Partially completed assignment).
- Optional, If you have taken PHP you may write your own PHP AboutNumber.php file, your output will need to be in XML format meeting the aboutNumber.xsd schema, Minnie wrote a Java program to calculate 16 bit Germain Primes and 32 bit Fermat numbers, you may use her XML code. You will have to use View source to see the actual PHP program.
- You need to unit test your JavaScript about Number functions. Goofy did this for Minnie Mouse see next bullet.
- It turns out Minnie was not smart enough to write the aboutNumber functions, however, she was smart enough to enlisted help from Goofy, Goofy was not only smart enough to write the aboutNumber functions, but he is also smart enough to include unit testing.
Java Programmers you can use Java Class, from JavaScript or you can test JavaScript using Java. We have an AboutNumber assignment in CS4B.
We can use just a standard form element w action to access this PHP file
But a jQuery
$( '#aboutNumber' ).post( "https://cim.saddleback.edu/~mmouse0/aboutNumber/aboutNumber.php",
{ number : formNumber.val } )
This will work if CORS is enabled in Minnie's folder. Currently CORS is not enabled for Mnnie's folder.
X1 (formerly H16) What's Hot
X1 Permalink and watch Canvas Webcast
Stack Overflow Trends looks like User Interface Frameworks (react.js (FaceBook)) and Server scripting using JavaScript (i.e., node.js ) are popular. Vu.js is not showing a lot of interest on stack overflow trends, but is the 2016 JavaScript award winner and is leading on github star. Nota Bene, not all projects use github. Also, over time since all questions have been answered, popular language have fewer new post. So you cannot use stack overflow trends to determine which languages are still popular. In the framework graph jQuery has fewer new posts, which makes sense its been around since 2007. In addition jQuery UI is popular, but we drag and drop and API is very good, so it a low number of posts.
Can rollover tag name to get specific tag graph in the Overflow Trend graph.
To determine whats hot we will look at Web Page Hits, CDN popularity, W3Schools, Stack Overflow, GitHub usage, tiobe.com, job site interest...
- Web Page Hits: Wappalyzer (jQuery, modernizer, jQuery UI, note react)
- CDN
Frameworks lists on google.apis: AngularJS, Angular Material, Dojo, Ext Core, jQuery, jQuery Mobile, jQuery UI, MooTools, Prototype, script.aculo.us, SPF, SWFObject, three.js (3D Graphics), Web Font Loader.W3Schools: Bootstrap, jQuery, jQueryMobile, AppML (Application Modeling Language; Bring Data to HTML), Angular.js,
- Note GitHut list JavasScript first( JavaScript, Java, Python, CSS, PHP) (Doesn't break JavaScript down into frameworks)
- stack overflow - (2016 most popular technologies JavaScript 55.4%, SQL 491.% Java 36.3%, C# 30.9%, PHP 25.9% Python 24.9%, C++, c, Node.js 17.2%, AngularJS 17.9%) (2015 JavaScript 54.4%, SQL 48%, Java 37.4%, .C#, PHP, Python, .C++, C, Node.js 13.3%, AngularJS 13.3%, Ruby, Objective-C)
- Basics matter, first master JavaScript, then move on to the framework, even jQuery has a lot less hits on indeed.com than basic JavaScript, Indeed.com JavaScript is coming up third in terms of programming languages.
- Tiobe JavaScript is 4th, (Java, C, C++, Python, C#, JavaScript, PHP) - note Go is the next big language, Objective-C is slipping because of swift
A lot of hype around React.js - 2015 Libraries to Watch (React.js, Rendr, Meteor)
Top Languages are Clearly: SQL (note Tiobe/githut don't list SQL it is a declarative language), Java, JavaScript, C's; Others have drop offs.
However some hot "fast growing" technologies are:
- JavaScript, framworks will come and go, but they are all based on JavaScript.
- jQuery, still in its early stage, (Bootstrap is based on jQuery), 1 is not upward compatible, 2 doesn't support IE7
- Framework 7 - android/IPhone framework
- jQuery Mobile, well integrated in DW, but is not that clean, I have a thumbs down for it.
- AngularJS, is just a JavaScript Expression language extension, lots of hype but have only bumped into two sites using it. W3C examples. - AngularUI
- Node.js - Serverside JavaScript, can be used for small devices? Java been used with small devices since 1989.
- Next generation of JavaScript is ECMAScript 6 ES6. due out soon, but shows limited support.(FF Firefox 8/15 version is 38 and 39). Since IE11 doesn't support it you have to wait until at least IE12/13. In recent years IE has gotten much better at supporting JavaScript, current *avaScript is ES5, support.
- Backbone.js Serverside *avaScript, Node.js competitor
- embedJS *avaScript framework for embedded devices.
- Bootstrap - HTML, CSS and *avaScript Framework, - W3C
- Modernizr - CSS3/HTML4 feature detector for browsers.
- Data Driven d3.js - lots of graphs couldn't find a line with square blocks.
- AppML not another expression language used to simplify AJAX/DOM traversal.
- jQuery Tools the missing User interface, supports RWD but doesn't have the equivalent jQuery UI themeRoller. Click samples, then standalone for code. Automatically loads jQuery. Note recent jQuery tools support ie6+, current jQuery UI has support ie8+. Accordion. Nota bene, jQuery tools 1.2 was way ahead of its time (2010-2012) release, but I cannot find out much about jQuery Tools 2.0, it may be a dead release.
- ember for Web Applications.
- MEAN stack (mongoloid/mongoose, express, angular, and node) - seems to be a popular bootcamp stack.; Express is a framework for node.js
- Apple swift, new language, replacing some Objective-C
- Grunt is a popular JavaScript task runner
Whats not Hot but Should be...
- Develop Once Platform Neutral Web Apps
- Flash ActionScript 3.0
- javaFX - Java Android development has increased Java interest. In terms of javaFX its too new t tell.
Note a lot of embedded controllers use Java as the main code (blue ray player) and scripting language like lua/python for interface (car GPS).
- JavaScript ( Bootstrap, anguar, ember ), HTML5 canvas and node.js server end. (Overhead heavy client)
- Client Bootstrap, HTML5, server Java EE
- PhoneGap - JavaScript Framework for access to native functionality: sencha, phone gap,
- jQuery Mobile git
Response to "added a 16th assignment to my JavaScript class on what is hot" from Two Professional JavaScript consultants...
.
Nathan Bailey Full Stack Software Engineer |
Hey Tom! |
MY WHAT'S HOT INPUT JavaScript Frameworks.
DESIGN:
OBJECTIVE-C REPLACEMENT
See the load time for the new pre-production Experian (native Bootstrap, Java EE, enterprise CMS) or my new company site (native Bootstrap, JavaScript, PHP):
I also want to make sure that Arvin gets through Comp Sci 4B before he leaves. Java may be the engine, but JSP is the presentation and JDBC is the fuel pipeline.
Lyndon Herzberg Here is that new mobile webframework I was talking about: http://www.idangero.us/framework7/ Here is why I like it: It takes basic JavaScript knowledge and lets you build native looking and acting applications incredibly quickly. There is no angular or MVC or anything like that, its just templates (inline or external) and jQuery style hooks to manage the life cycle of each one.
Super productive and easy to learn and their jQuery replacement API is pretty much jQuery compatible so instead of $('.class') its $$('.class') and you are off to the races. |
Web Page Assignment.
Watch 5/13/3015 Web-casts, take notes and comment on your findings. Then identify what you feel are the five most significant JavaScript libraries and why. You summary should at least 250 words long, you may want to include examples of each library in your summary. Bootstrap and jQuery should be relatively easy to use at this stage.
X2 RWD Frameworks - Bootstrap/Skeleton
X2 Permalink and watch Canvas Webcast
Tentative Bootstrap Book
- Series: Sams Teach Yourself Bootstrap
- Paperback: 432 pages
- Publisher: Sams Publishing; 1 edition (November 14, 2015)
- Language: English
- ISBN-10: 0672337045
- Valorebooks.com $20 | Amazon $20 also
Basics Matter! I have seen so many students in the last 2 years fooling around with Bootstrap, and running into major problems because they don't have the basics. Basics matter, if you have not taken cimw115 take it. If you are not sure about Dreamweaver's site definition, files and/or folders make sure you re-watch the entire cimw115 cim-dreamweaver video set.
- 2014 Best Frameworks
- Wappalyzer Bootstrap - ASP.net - INK - Foundation; Problem more Server Side (RoR) and are not RWD. INK is part of Foundation and ASP.net is MVVC not really an RWD.
Modern day RWD (Responsive Web Design) CSS frameworks fall into two groups lightweight and heavyweight. Lightweight frameworks provide the skeleton (aka 2by4 framework) for an RWD site, they have little if any JavaScript, and have a streamlined CSS file. Since they are lightweight, its easy to comprehend the code. Lightweight systems don't provide default formatting of your content. In addition you can load your own JavaScript libraries. However, the JavaScript libraries may or may not be RWD. The most popular lightweight systems are...
- Skeleton simple light weight
- Simple Grid lightweight
- Pure.css - Yahoo CSS Framework
In order to maintain compatibility with jQuery UI components and all the CSS design students have written the future cimw160 website will be based on Skeleton.
Heavyweight RWD frameworks, provide not only the RWD framework, but also entire JavaScript frameworks, JavaScript user interface components, and content formatting. The most popular heavyweight RWD frameworks are...
- Foundation geared for Web Applications
- twitter Bootstrap most popular mobile first RWD framework
If you are starting brand new project then heavyweight framework may be the best tool for the job. However, if you already have a lot of custom CSS code and JavaScript then lightweight is probably the best path to take. Latest version of Dreamweaver cloud provides full support for Bootstrap, Bootstrap provides an RWD framework, and its own set of user interface tools (DW Bootstrap components) very similar to jQuery UI. Nota bene, Bootstrap is a heavy weight system you have to be good with a powerful IDE like Dreamweaver in order to use.
Web Page Assignment
For this assignment chose one of the frameworks above and redesign you home page using it. Make sure you home page has links to your assignment. Also include a short narrative why you chose that framework. You may start with this canned bootstrap file.
Notebook Addenda
- What is the key difference between a lightweight and heavyweight RWD framework.
- Why would you use a lightweight over a heavyweight framework.
CIMW140 CSS/RWD discuss the grid system layouts of the above RWD frameworks. The problem with these frameworks, they don't balance content size. CIMW140 also covers a more modern layout, called Flexbox.
Bootstrap has deprecated jQuery Mobile and Fluid Grid.
Other - jQuery Ideas
Query Assignment Titles (J4 not updated to Bootstrap yet, x2 WIP)..
- jQuery Selector J1
- jQuery Events/Methods/Animation J2
- jQuery UI User Interface J3
- jQuery AJAX and DOM intro.J4, J5
- Whats HOT X1
- Bootstrap RWD X2
- may create simple essay on phone gap, sencha, and jQuery mobile w example on cim
- RWD example
- Google is using angular JS at the front end.
- Calendar: jQuery - server side
- using gmaps.js, take a look at mapbox
- jQuery Amazon API (books) w XML class list E-Commerce smashup
- skip Adobe Edge jQuery RAD Animation
- Flash do it once run everywhere environments: adobe air, flex
- NetBeans or JavaScript debuggers - jsPerf site
- Advance JavaScript Web Application RAD tool most likely wave-maker - dojo Framework
deprecated JavaScript Special Effects - UI Framework
Updated laster to jQuery plug Ins. Could add geolocation to h15
Web-based reading assignment: Brief intro to jQuery JavaScript framework, watch Canvas assignment Web-cast, JavaScript Library, Frameworks. Note the default JavaScript library (aka API) is not extensive enough to cover the building of Web applications, therefore users have created library and frameworks which have predefined functionality and classes to help in the development of Web applications.
Log File Addendum: Briefly contrast JavaScript snippet, library and frameworks. Comment on top sites used to download JavaScript snippet. Identify the JavaScript snippet used here, where did it come from. This site illustrates various JavaScript snippets. Try out a few of the snippets including the print example. Most of my class sites also have a print button, how do you set up the JavaScript for this print function? The CSS is relative easy simply have a style sheet set to media="print" (you can also use the @media annotation).. Briefly define a JavaScript framework and comment on this comparison. A JavaScript framework provides you with additional libraries/classes to automate regularly used procedures (e.g., form validation). The User Interface (UI) is a library built onto of the framework to supply a rich user interface. Briefly comment on this comparison of User Interface (UI) Frameworks, P.S. jQuery has become very popular recently, but JavaScript over all is a lot more popular. The UI site for jQuery is jQuery UI. JavaScript Framework job comparison...
Web Page assignment: Create a Web page with three JavaScript special effects:
- Your first JavaScript special effect needs to be the wheel discussed above, but modify it so that it steps through your assignments, (it currently steps through the classes).
- The Second one is of your choosing, you can use any special effect snippet or preferably UI Framework effect. For example, use a popular snippet, Google Web Toolkit special effects, GWT-fx, or DW Spry behavior, (DW Spry Window--> Behaviors(Dialog Panel), Select Age Behaviors, + Menu Has Many Effect (swap image), extra options sub menu Effects & More Effects)
- Third review the live examples below, and try to write your own modeled after the live examples.
- Alert Box pop up
- Prompt window with document.write
- Button with onclick event to display date.
Checklist
- Make sure log file and assignments are up to date (no new quizzes this time)
Final Class Reminders aka Final Checklist:
- Canvas Quizzes maintain final due dates
- Make sure you have completed all Canvas quizzes
- Refer to syllabus make sure you have completed to assignments you need for the grade you want.
- jQuery Assignments are not that hard.
- Reminder Canvas announcements are used to inform students of course updates.
Thanks for taking the class, cimw 280 Portfolio, cimw 140 CSS/RWD and cimw 245 Intro PHP, CMS WordPress and E-Commerce are good classes to take next.