IP356W12A

From CourseWiki

Jump to: navigation, search


JavaScript Introduction

Overview

Client-side scripting (at the browser) is a common method of bringing interactivity to the user experience on the web.

Learn about one of the most popular (widely supported) tools for doing this: JavaScript

This course provides a hands-on introduction to programming in JavaScript, general scripting fundamentals as well as JavaScript specifics (80% of the course). We will also explore using the jQuery JavaScript Library (20% of the course).

Duration: 12 hours

Register for this course

Objectives

Theoretical Objectives

  • Understand how JavaScript fits into the context of web development
  • Understand where JavaScripts fits into the context of specific web pages
  • Understand these concepts of programming in JavaScript:
    • Sequence
    • Variables
    • Functions
    • Selection
    • Iteration
    • Arrays
    • Object Orientation
  • Understand how JavaScript is related to the Document Object Model and how JavaScript can manipulate and otherwise affect an HTML document
  • Know where to find and how to use JavaScript libraries and utilities
  •  Understand where jQuery fits in the context of JavaScript

Practical Objectives

  • Create web pages that use JavaScript to:
    • Dynamically write content to web page
    • Create user interfaces using forms
    • Create pop-up messages to inform and capture user input
    • Create functions to
      • Encapsulate business logic
      • Dynamically update the current web page
  • Introduction to jQuery
    • Use jQuery within a web page to manipulate CSS properties
    • Use jQuery UI (User Interface) libraries in web page

 

Prerequisites

Academic

The better you understand HTML - the more you will take from this course.

Technical

Access to the Internet You will need to FTP files from / to our server to / from your remote location in order to successfully complete the assignment
  • Setup for Examples

  1. Student Home Page Maker
  2. Student Template Page Maker View the Source of this page, then save the text to your local hard drive (c:\My Documents) as your_name99.htm (note - you will have to force the extension to htm).
  3. Style Sheet to go with Template Save this file to your local hard drive (c:\My Documents) as Styles.css


  • Tools


Computer Equipment

The sessions are conducted in a computer lab, and you will have a computer provided for your use. You are welcome to bring your own computer to the lab sessions if you prefer to use that. Wireless access is available in the lab.

Please note that at times you will be doing a fair bit of typing and you will want to have a large enough screen and separate physical keyboard so that you can view content and type at the same time.

If it appears that you are having challenges with your own device, we will ask you to use the computer provided for you in the lab.

Storage

Please plan to use your own cloud based storage SkyDrive, DropBox, iCloud (or similar) or a USB storage key.

Instructional Methods

  • Hands-on labs
  • Discussion
  • Online collaboration
  • Homework assignments submitted online
  • Lecture

Course Materials

  • Web site
  • Course notes
  • Printed copies of on-screen lecture notes available on request during lectures

No Recording or Pictures in the Lab

Please note: Taking pictures or video during the course sessions is not permitted. All the course materials and lecture notes are available in physical form and on the web.


Requirements for Completion
  • Attend all sessions
  • Participate in class workshops with others (pairs and small group work)
  • Complete assignments: Typically this involves:
  • Entry in the course blog every week
  • Questions and Answers in PeerWise:
    • Create questions online: minimum 1 per week - due by midnight Mondays
    • Answer all unanswered questions online: minimum 5 per week - due by 5:00 pm Tuesdays
  • Creating web pages that use concepts introduced each week.

See tabs for each week.


Contents

Jim's Start Up Resources


Coming Soon
Courses coming

Follow JimUBC on Twitter for latest course updates
Follow JimUBC on Twitter for latest course updates
Course Blog
Follow JimUBC's blog for latest course updates


Demo site

Search JavaScript Examples and Concepts

Loading


Blog for this session Join the conversation.

  • Peerwise
  • Peerwise Course ID: 8144
  • Course Identifier IP356W12A (all lower case)

Course Evaluation Form


WebMatrix Publish Settings
  1. Download
  2. Double-click the file and extract (drag) the contents to the desktop
  3. Start WebMatrix
  4. Click Open
  5. Click Remote
  6. Import Publish Profile
  7. Navigate to the desktop and double-click ip356.azurewebsites.net.publishsettings
  8. voilà

FTP Method

ftp host name: ftp://waws-prod-bay-001.ftp.azurewebsites.windows.net

site path: /site/wwwroot

user name: ip356\ip491

password: provided in your course notes

destination url: http://ip356.azurewebsites.net


Thank you to Adam for providing these screen shots of his FileZilla settings.

Note: Encryption: Only use plain FTP

Note: Path is /site/wwwroot




Session One

At the end of this session (and after completion of the session one assignment) you should be able to
  • Identity the three main technologies that comprise the modern web
  • Define JavaScript:
    • Scripting language
    • In the context of HTML
    • Know where to find it in a web page
  • Create your JavaScript development environment (UBC FTP site and jsbin )
  • Use a JavaScript library within your HTML5 web page
  • Use an online tool to validate your HTML5 web pages
  • Log into PeerWise to create and answer questions.

Journal

  • What do you know about JavaScript?
  • What have you already done with JavaScript?
  • Have you written any JavaScript in your web pages? What questions did you have about the process?

To prepare for this session we will

    1 Session One

Reading

Review and consolidate concepts:
JavaScript Overview
Preparation for next session:
JavaScript Guide: Grammar and Types

Update Your Pages
  1. Change the Descriptions for the files we created in the first session, so that those descriptions are meaningful to you.
  2. Use WebMatrix, Visual Studio, or FTP to upload your homepage and page 01 to the UBC Server


WebMatrix (Windows Clients only)

WebMatrix is the editor/ftp client that we are using in the lab. Download it here: WebMatrix

Note: Once you have your site created (what we are doing here), you can then access it from "My Sites" above.


WebMatrix Publish Settings
  1. Download
  2. Double-click the file and extract (drag) the contents to the desktop
  3. Start WebMatrix
  4. Click Open
  5. Click Remote
  6. Import Publish Profile
  7. Navigate to the desktop and double-click ip356.azurewebsites.net.publishsettings
  8. voilà

OR

FTP Method
  1. Use an ftp client (e.g. Filezilla) to download your homepage from
    http://ip356.azurewebsites.net


ftp host name: ftp://waws-prod-bay-001.ftp.azurewebsites.windows.net

site path: site/wwwroot

user name: ip356\ip491

destination url: http://ip356.azurewebsites.net


Thank you Adam for providing these screen shots of his FileZilla settings.

Image:FileZillaIP356F15A1.png

Image:FileZillaIP356F15A2.png

Image:FileZillaIP356F15A3.png


If you have questions about JavaScript or this assignment - please post them in the course blog (Session One Notes). If you spot a question from someone else and you can answer it - please do.

  • Login in to PeerWise :IP356W12A
  • Create at least one new question.
  • Answer at least five questions.
    • Correct your answers if necessary.
      • Confirm your answers as you go along.
    • Help where you can to improve explanations.
    • Add comments in the questions.
    • Rate the questions.

Detailed Instructions

Reflect in the course blog


Please click the picture above and answer the following questions in the course blog.

Highlights / Metacognition
  • What did you think was the most valuable thing that happened for you tonight?
  • What did you learn from that?
  • What will you do with that knowledge?
Questions?
  • Now that we've had our session together, what do you want to know?
  • What could we have done better?

Course Blog Tutorial (video)

External links / resources

A little history


Course Overview / Introduction

javascript01.gif

  1. Big Web
  2. JavaScript defined:

What It Is

Definitions

  • JavaScript is the scripting language of the Internet. It is the most popular scripting language on the World Wide Web and is used in millions of Web pages to power rich, interactive content and increasingly powerful web applications. JavaScript is the "glue" ...
  • JavaScript is an interpreted, high-level language like BASIC, yet it has a syntax similar to C and Java. This makes it easy to learn, easy to test, and easy to debug. An interpreter (also known as an "engine") takes the high-level, plain-text JavaScript code and translates it on the fly into native instructions on the current machine.
JavaScript is the Netscape-developed object scripting language used in millions of web pages and server applications worldwide. Netscape's JavaScript is a superset of the ECMA-262 Edition 3 (ECMAScript) standard scripting language, with only mild differences from the published standard.
Contrary to popular misconception, JavaScript is not "Interpretive Java". In a nutshell, JavaScript is a dynamic scripting language supporting prototype based object construction. The basic syntax is intentionally similar to both Java and C++ to reduce the number of new concepts required to learn the language. Language constructs, such as if statements, for and while loops, and switch and try ... catch blocks function the same as in these languages (or nearly so.)
JavaScript can function as both a procedural and an object oriented language. Objects are created programmatically in JavaScript, by attaching methods and properties to otherwise empty objects at run time, as opposed to the syntactic class definitions common in compiled languages like C++ and Java. Once an object has been constructed it can be used as a blueprint (or prototype) for creating similar objects.
JavaScript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via eval), object introspection (via for ... in), and source code recovery (JavaScript programs can decompile function bodies back into their source text) Intrinsic objects are Number, String, Boolean, Date, RegExp, and Math. ...
JavaScript is not "Interpretive Java". In a nutshell, JavaScript is a dynamic scripting language supporting prototype based object construction.

See also: ECMA Script

Where JavaScript Lives

What JavaScript Can Do

Scripting Datatypes and Syntax

Scripting and Data Types

Enter a simple numbertext1
Another simple numbertext2
Another numbertext3
Click for the total text4
Click for the total text5

Related reading: An Introduction To Programming Type Systems

Syntax

Lines of JavaScript with out semi colons (sic) are a challenge
to the JavaScript interpreter; like this is in English.

that that is is that that is not is not is that it it is


Automatic Semicolon Insertion

Although JavaScript has C style syntax, it does not enforce the use of semicolons in the source code, so it is possible to omit them.

JavaScript is not a semicolon-less language. In fact, it needs the semicolons in order to understand the source code. Therefore, the JavaScript parser automatically inserts them whenever it encounters a parse error due to a missing semicolon.

– Javascript-Garden[1]

var foo = function() {
} // parse error, semicolon expected
test()
Insertion happens, and the parser tries again.
var foo = function() {
}; // no error, parser continues
test()

Going forward put opening curly brace immediately after the function definition parentheses

function myFunction() {
// function statements here
};

Do not put the opening curly brace on a separate line.

function myFunction() 
{
// function statements here
};


Beautiful Syntax

From: idiomatic.js Beautiful Syntax

// if/else/for/while/try always have spaces, braces and span multiple lines
// this encourages readability
 
// 2.A.1.1
// Examples of really cramped syntax
 
if(condition) doSomething();
 
while(condition) iterating++;
 
for(var i=0;i<100;i++) someIterativeFn();
 
// 2.A.1.1
// Use whitespace to promote readability
 
if ( condition ) {
  // statements
}
 
while ( condition ) {
  // statements
}
 
for ( var i = 0; i < 100; i++ ) {
  // statements
}
 
// Even better:
 
var i,
  length = 100;
 
for ( i = 0; i < length; i++ ) {
  // statements
}
 
// Or...
 
var i = 0,
  length = 100;
 
for ( ; i < length; i++ ) {
  // statements
}
 
var prop;
 
for ( prop in object ) {
  // statements
}
 
if ( true ) {
  // statements
} else {
  // statements
}

– Source: idiomatic.js[1]


What Do I Need

During our lab sessions we will use WebMatrix

If choose not to use WebMatrix for your work when you are not in the lab you will need:


References


PeerWise Sample Questions

  1. JavaScript can be written or stored in four places. Pick the correct answer. head, body, external file, end of body
  2. JavaScript is related to which language: Java, Visual Basic, C, C++, None of these.
  3. JavaScript is compiled at the: server, browser, integrated development language, None of these.
  4. JavaScript is can create new instances of: HTML Elements, JavaScript Objects, JavaScript Variables, CSS Styles, All of these.
  5. JavaScript can run dynamic interactive animations.
  6. JavaScript is required to do offline storage in HTML5.
  7. JavaScript is: object oriented, prototype oriented, anamorphic, polymorphic, something else. Reference: Introduction to Object Oriented JavaScript
  8. JavaScript is strongly typed, loosely typed, dynamically typed typed, strictly typed when you use "use strict". Reference: JavaScript Datatypes, Dynamically typed languages, Strict Mode
  9. JavaScript has Predefined Core Objects relies on objects that are predefined in the JavaScript language and HTML Elements.
  10. JavaScript requires semicolons at the end of every line, at the end of every statement, at the end of functions, after all closing curly braces }
  11. JavaScript is case sensitive, case insensitive, sensitive to white space, requires line numbers.

Examples

  1. Student Home Page Maker
  2. Use WebMatrix to access the student work site, create a page firstname_lastname.html and copy the content from the Home Page Maker into it.
  3. Create a new page firstname_lastname30.html
  4. Open zStudentTemplate.html and copy the contents into your firstname_lastname30.html page
  5. Close zStudentTemplate.html
  6. In firstname_lastname30.html on line 10, add your name First Last
  7. To create new examples create a new page firstname_lastname99.html (99=current number).
    Open firstname_lastname30.html, copy the contents into the new page
    Close firstname_lastname30.html

  8. Session One Examples

    Session One Examples

    Assignment 01

    Reading

    Review and consolidate concepts:
    JavaScript Overview
    Preparation for next session:
    JavaScript Guide: Grammar and Types

    Update Your Pages
    1. Change the Descriptions for the files we created in the first session, so that those descriptions are meaningful to you.
    2. Use WebMatrix, Visual Studio, or FTP to upload your homepage and page 01 to the UBC Server


    WebMatrix (Windows Clients only)

    WebMatrix is the editor/ftp client that we are using in the lab. Download it here: WebMatrix

    Note: Once you have your site created (what we are doing here), you can then access it from "My Sites" above.


    WebMatrix Publish Settings
    1. Download
    2. Double-click the file and extract (drag) the contents to the desktop
    3. Start WebMatrix
    4. Click Open
    5. Click Remote
    6. Import Publish Profile
    7. Navigate to the desktop and double-click ip356.azurewebsites.net.publishsettings
    8. voilà

    OR

    FTP Method
    1. Use an ftp client (e.g. Filezilla) to download your homepage from
      http://ip356.azurewebsites.net


    ftp host name: ftp://waws-prod-bay-001.ftp.azurewebsites.windows.net

    site path: site/wwwroot

    user name: ip356\ip491

    destination url: http://ip356.azurewebsites.net


    Thank you Adam for providing these screen shots of his FileZilla settings.

    Image:FileZillaIP356F15A1.png

    Image:FileZillaIP356F15A2.png

    Image:FileZillaIP356F15A3.png



    Session Two

    At the end of this session (and after completion of the session one assignment) you should be able to
    • Review JavaScript:
      • Scripting language
      • In the context of HTML
      • Know where to find it in a web page
    • Extend your JavaScript development environment with jsbin
    • Log into PeerWise to create and answer questions.
    • Create JavaScript Functions
      • with and without return values
      • with and without parameters
    • Create an HTML form that calls JavaScript functions
    • Use several methods of the JavaScript String Object
    • Use conditional branching, iteration, arrays

    Journal

    • Have you looked at any JavaScript scripts in the last week?
      • What did you notice?
    • Can you define the terms
      • variable
      • array
      • sequence
      • selection / conditional branching
      • iteration

    To prepare for this session we will

    • Discuss issues arising from homework assignment
    • Review the old your_name.js footer function

      1 Session Two

    Reading

    Consolidation and review:

    Reading ahead:


    Writing Pages
    • Switch: Build your own version of Switch - call it your_name03.html
    • Complete the assignments we started in class - see your html pages for instructions that you wrote. This can include migrating things we did in jsbin into full web pages (e.g. your_name04.html
    Optional
    • Function: Create a page your_name05.html so that it accepts user input for one or two parameters in a function that you create. You don't HAVE to create a user interface for the user to provide the parameters, but if you want to, create a form and allow the user to provide data that you use in the function.

    What the function does is completely up to you. But the outcome should be visible in the page (probably with window.alert()). If you can't think of a reason to build web page with a function, try figuring out a dog's age in dog years.

    You may use any of these Session 2 Models for ideas.

    Add a reference to this page in your 00.html table of contents too.

    Save the page as your firstName_yourlastName05.html and use FTP or WebMatrix to publish it to the student work site.

    Dog Years Algorithm

    If you can't think of a function you can try this something based on this:


    Formula for dogs less than 20lbs is y=4.1464x + 14.429
    Dogs 20-50lbs is y= 4.6107x + 14.111
    Dogs 50-90lbs is y= 5.457x + 11.61
    And, finally... Dogs 90 lbs plus is: y = 7.325x + 5.2667


    Reading Ahead
    JavaScript Events / Closures / Anonymous Functions

    Please relax and read for light understanding


    If you have questions about JavaScript or this assignment - please post them in the course blog (Session One Notes). If you spot a question from someone else and you can answer it - please do.

    • Login in to PeerWise :IP356W12A
    • Create at least one new question.
    • Answer at least five questions.
      • Correct your answers if necessary.
        • Confirm your answers as you go along.
      • Help where you can to improve explanations.
      • Add comments in the questions.
      • Rate the questions.

    Detailed Instructions

    Reflect in the course blog


    Please click the picture above and answer the following questions in the course blog.

    Highlights / Metacognition
    • What did you think was the most valuable thing that happened for you tonight?
    • What did you learn from that?
    • What will you do with that knowledge?
    Questions?
    • Now that we've had our session together, what do you want to know?
    • What could we have done better?

    Course Blog Tutorial (video)

    External links / resources

    A little history


    Startup - JavaScript Libraries

    JavaScript Library

    Review

    Create your own JavaScript library.

    your_name.js

    Put your footer function in the library. You can cut this out of your_name30.html template. You should be able to read and understand this by the end of this session.

    function footer(docName) {
      var copydate=new Date();
      var copyyear=copydate.getFullYear();
    // if the parameter docName is not null (empty) 
    //    use it, or else use window.location.href
      docName = docName || window.location.href;
      document.write(" Last updated on " + document.lastModified);
      document.write(" " + document.title);
      document.write(" Document  "+ docName.bold() );
      document.write(" Copyright &copy; "+ copyyear );
      document.write(" All Rights Reserved ");
    }  // end function


    Amend your template to call the library.

    <script src="your_name.js">
    // Do not add any code here. It will NOT execute.
    </script>
    Addition to your Stylesheet

    Optional discussion.


    /* form labels */
    label { 
    float:left;
    width:150px;
    text-align:right;
    margin-right:10px;
    }
    label:after{
    content:  ":" ;
    }

    Understanding the Template and Footer and More

    Section 1 String.replace() and link

    Standard built-in objects: String

    replace()

    var strFullName = "Sheldon Cooper";
    var strFull_Name = strFullName.replace(" ","_");
    document.write(strFull_Name);

    Output is Sheldon_Cooper

    Reference JavaScript Reference:Replace

    link()

    var strLinkText = "University of British Columbia";
    var strUBCLink = strLinkText.link("http://www.ubc.ca");
    document.write(strUBCLink);

    Output is University of British Columbia

    Reference: JavaScript Reference:Link

    Section 2 How this applies to your Template

    Review assignments - Group Discussion

    Update to Template JavaScript_StudentTemplate.html

    Here it is as it appears in your template pages now starting on line 9


    // Please put your name in the variable below between the quotes
    var strMyName = "";
    var strHomeLink="<a href=\""+strMyName.replace(" ","_")+"00.html"+"\">home</a>";

    Here is another approach to creating the link.


    // Please put your name in the variable below between the quotes
    var strMyName = "";
    var strHomeLink= "home".link(strMyName.replace(" ","_").toLowerCase()+"00.html");  


    Section 3 Language Basics - Are we there yet?

    JavaScript MindMap

    1. Syntax
      • Statements
      • Expressions
      • Data Types
          Primary (primitive) Data Types
        • String
        • Number
        • Boolean
          Composite Data Types
        • Array
        • Object
          Special Data Types
        • Null
        • Undefined
    2. Language Structures
      • Branching
      • Iteration
    3. Language Concepts
      • Objects
      • Properties
      • Methods
      • Events
    4. Reserved Words
    5. Models and examples for this week


    JSBIN a quick introduction

    Here's another tool to use for your JavaScript development. Note: jsbin is a wonderful environment in which to learn concepts and test ideas but you still need to be able to create full web pages, and you may find that once you have developed your ideas and coded them, you will need to migrate things to separate files.


    • Create an account with jsbin — Write down your credentials so you can continue your explorations later.
      Image:jsbinJavaScript001.png
    1. Close the blue area at the top
    2. Login / Register
    3. First time? Register with GitHub
    Quick tips
    • Clear the Console: ctrl-l (L)
    • Clear the Output window: click the Run with JS button


    JavaScript Functions

    Concepts and Syntax

    Functions allow you to define an action or activity and then call it later, on demand. Typically you define the function in the <head> section of your page and then call that function in the <body>.
    Block Statement: A block statement is used to group statements. The block is delimited by a pair of curly brackets.  { }  : Block statements are commonly used with control flow statements (e.g. if, for, while).

    Preferred form

    Variations


    No Parameters or Return Statement

    In the function in shown below, we are not using parameters or a return statement.

    This is not very interesting or useful because it always does the same thing.

    Parameter

    Function with a parameter, but no return statement.

    Return Statement

    Function with a parameter, and a return statement.


    Functions Calling Functions

    Functions may contain any JavaScript including calls to other functions.
    Now call the function.

    Parameters (more than one)

    More than one parameter? Separate them with commas.

    Function Scope

    Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function and any other variable to which the parent function has access.
    Function Scope




    Methods of JavaScript string prototype (object)

    String Type

    JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.

    Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example:

    • A substring of the original by picking individual letters or using String.substr().
    • A concatenation of two strings using the concatenation operator (+) or String.concat().

    Example
    string.substr() and string.concat()

    String Object

    String Literals (Primitives) and String Objects
    String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.


    Global Objects

    Methods of the String Object

    Methods of the JavaScript string object

    str.toUpperCase() str.toLowerCase()

    String.prototype.toLowerCase() String.prototype.toUpperCase()

    str.replace("old value","new value")

    String.prototype.replace()



    JavaScript and Forms

    Getting User Input with a Form

    Sometimes we need a user to provide some data that we can manipulate in JavaScript. Let's use a form for that.



    The function greetings(first, last)



    There's a little CSS styling going on here too. Here is the CSS that formats the actual form. We won't get into this because that's for another course.

    see it live


    More String Methods and Forms

    Combining Methods






    The Form that uses email()

    See the live demo in jsbin


    Session Two: Hands On

    For this session we will us jsbin

    Please register / login before proceeding.

    Show me JSBIN


    • Create an account with jsbin — Write down your credentials so you can continue your explorations later.
      Image:jsbinJavaScript001.png
    1. Close the blue area at the top
    2. Login / Register
    3. First time? Register with GitHub
    Quick tips
    • Clear the Console: ctrl-l (L)
    • Clear the Output window: click the Run with JS button

    Hands on with IF, FOR, WHILE, ARRAYS

    Conditional Branching with IF

    Close the Console. Open the JavaScript window, and enter this in the JavaScript window.

    Image:JsbinJavaScript004.png

    live version - conditional branching

    exploring If and Switch (much more detailed example)

    Iterations with FOR


    Here's how it looks.


    Image:JsbinJavaScript005.png

    live version - iteration

    Iterations with WHILE and DO ... WHILE

    live version exploring iteration with while and do ... while

    Arrays introduction


    Here's how it looks

    Image:JsbinJavaScript006.png

    live version - arrays




    Assignment Two

    To be completed before Monday March 12, 2012

    Reading

    Consolidation and review:

    Reading ahead:


    Writing Pages
    • Switch: Build your own version of Switch - call it your_name03.html
    • Complete the assignments we started in class - see your html pages for instructions that you wrote. This can include migrating things we did in jsbin into full web pages (e.g. your_name04.html
    Optional
    • Function: Create a page your_name05.html so that it accepts user input for one or two parameters in a function that you create. You don't HAVE to create a user interface for the user to provide the parameters, but if you want to, create a form and allow the user to provide data that you use in the function.

    What the function does is completely up to you. But the outcome should be visible in the page (probably with window.alert()). If you can't think of a reason to build web page with a function, try figuring out a dog's age in dog years.

    You may use any of these Session 2 Models for ideas.

    Add a reference to this page in your 00.html table of contents too.

    Save the page as your firstName_yourlastName05.html and use FTP or WebMatrix to publish it to the student work site.

    Dog Years Algorithm

    If you can't think of a function you can try this something based on this:


    Formula for dogs less than 20lbs is y=4.1464x + 14.429
    Dogs 20-50lbs is y= 4.6107x + 14.111
    Dogs 50-90lbs is y= 5.457x + 11.61
    And, finally... Dogs 90 lbs plus is: y = 7.325x + 5.2667


    Reading Ahead
    JavaScript Events / Closures / Anonymous Functions

    Please relax and read for light understanding


    If you are testing with Internet Explorer consider allowing blocked content

    Image:AllowBlockedContent.jpg

    Session Three

    At the end of this session (and after completion of the session one assignment) you should be able to
    • Identify objects by TagNames, ClassNames, IDs within an HTML document. (Document Object Model)
    • Use JavaScript to manipulate objects within the HTML document.
      • Understand this JavaScript statement:
        var element = document.getElementById("id");
    • Use event handlers.
    • Create event listeners.
    • Create arrays.
      • Retrieve data from arrays.
      • Iterate over an array.
    • Discuss the Principles of Unobtrusive JavaScript.

    Journal

    Next Steps

    HTML5 3: Building Dynamic Experiences with JavaScript Starts Tuesday November 24 - December 15, 2015, 06:30pm to 09:30pm, register by Monday November 23rd.
    jQuery: Beyond Fundamentals Starts Wednesday November 25 - December 16, 2015, 06:30pm to 09:30pm - please register by the Tuesday November 24th.

    • What are some of the disadvantages of document.write()?
    • What do you know about the Document Object Model

    To prepare for this session we will

    1. Review assignments - Group Discussion
    2. Homework assignments: Working in pairs, share your work.
      1. What worked?
      2. What didn't?
      3. What was the most challenging?
    3. See working with forms

      1 Session Three
    Read Document Object Model Introduction


    Comment in the Course Blog

    Session Three Notes

    Hands On

    You can use jsbin or similar tool to create and test your JavaScript but you must then make that code work in a page your_nameNN.html that is linked to your homepage on course ftp server. The objective is to ensure that you know how to work outside the jsbin environment.

    HINT: Download your work in jsbin (see: File | Download) and study where the JavaScript code resides in the document.
    Hint, Hint... Put your JavaScript at the bottom of your page so that the document is complete before you attempt to make references to IDs or TagNames or Classes.

    document.getElementById("")

    Consider this example that used document.getElementById : Simple Chalkboard example or Prettier Chalkboard example

    Create a page your_nameNN.html that writes content to ( sets the .innerHTML )

    <div id="javascriptOutput">

    You can make that as simple or challenging as you like.

    Simple: Write a string

    Challenging: Create a user input form and process the responses and then write to the <div>

    Event Handling

    Consider this example that used document.getElementById : Event Handlers Inline, ById, ByTagName, ByClassName

    Create another page your_nameNN.html that has at least two different event handlers.

    The event handlers must do something visible like change the .innerHTML of a div or change a style attribute. If you are familiar with CSS you can .addClass or .removeClass.

    Background Reading

    Catchup reading: Consolidation and review:

    Unobtrusive JavaScript


    Reading: JavaScript Events / Closures / Anonymous Functions

    These articles were in the session two assignment. If you haven't already read them please relax and read for light understanding

    PeerWise

    Create a new question by Tuesday night. Answer all unanswered questions by Wednesday before the next class. Please rate the questions as you do them.

    If you have questions about JavaScript or this assignment - please post them in the course blog (Session One Notes). If you spot a question from someone else and you can answer it - please do.

    • Login in to PeerWise :IP356W12A
    • Create at least one new question.
    • Answer at least five questions.
      • Correct your answers if necessary.
        • Confirm your answers as you go along.
      • Help where you can to improve explanations.
      • Add comments in the questions.
      • Rate the questions.

    Detailed Instructions

    Reflect in the course blog


    Please click the picture above and answer the following questions in the course blog.

    Highlights / Metacognition
    • What did you think was the most valuable thing that happened for you tonight?
    • What did you learn from that?
    • What will you do with that knowledge?
    Questions?
    • Now that we've had our session together, what do you want to know?
    • What could we have done better?

    Course Blog Tutorial (video)

    External links / resources

    A little history


    Overview and Reference

    Section 1 Ramping Up

    Next Steps

    HTML5 3: Building Dynamic Experiences with JavaScript Starts Tuesday November 24 - December 15, 2015, 06:30pm to 09:30pm, register by Monday November 23rd.
    jQuery: Beyond Fundamentals Starts Wednesday November 25 - December 16, 2015, 06:30pm to 09:30pm - please register by the Tuesday November 24th.

    Dog Years Algorithm

    From session 2 homework. Dog Years in jsBin

    Looking Back

    JavaScript Guide: Statements
    Metacognition
    The course blog
    PeerWise
    any challenging questions?
    Review assignments - Group Discussion
    Homework assignments: Working in pairs, share your work.
    • What worked?
    • What didn't?
    • What was the most challenging?
    See working with forms

    Section 2 document.getElementById

    Summary

    Returns a reference to the element whose ID is specified.

    Syntax

    var element = document.getElementById("id");

    • element is a reference to an element object.
    • id is a case-sensitive string representing the unique ID of the element being sought.

    Chalkboard example
    Source: document.getElementByid
    See document.getElementById
    Related:
    document.getElementsByTagName
    document.getElementsByClassName

    Section 3 Arrays


    Review: Arrays

    Discuss Form Elements and Arrays

    Section 4 document.getElementsByTagName

    Summary

    Returns an HTMLCollection of elements with the given tag name. The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.

    Syntax

    var elements = document.getElementsByTagName(name);

    • elements is a live HTMLCollection of found elements in the order they appear in the tree.
    • name is a string representing the name of the elements. The special string "*" represents all elements.

    Event Handlers Inline, ById, ByTagName, ByClassName — jsbin
    Source: document.getElementsByTagName
    Related:
    document.getElementById
    document.getElementsByClassName

    Section 5 document.getElementsByClassName

    Summary

    Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

    Syntax

    var elements = document.getElementsByClassName(names);

    • elements is a live HTMLCollection of found elements.
    • names is a string representing the list of class names to match; class names are separated by whitespace.
    • element is any Element of a document.

    Event Handlers Inline, ById, ByTagName, ByClassName — jsbin
    Source: document.getElementsByClassName
    Related:
    document.getElementById
    document.getElementsByTagName

    Section 6 Language Basics - Are we there yet?

    JavaScript Predefined Core Objects
    Let's look specifically at the String object

    JavaScript MindMap

    1. Syntax
      • Statements
      • Expressions
      • Data Types
    2. Language Structures
      • Branching
      • Iteration
    3. Language Concepts
      • Objects
      • Properties
      • Methods
      • Events

    Section 7 No JavaScript



    What: No JavaScript?

    <head>
      <noscript>
        <meta http-equiv="refresh" content="0; url=http://myserver.com/pageToViewIfNoJavaScript.html" />
      </noscript>
     
      <script>
        location.replace('http://myserver.com/anotherPageWithJavaScript.html');
      </script>
    </head>



    And this week we will continue to use jsbin. This is great tool for development, teaching, sharing, debugging, but ultimately you still have to create pages. So use tools like this wisely but don't become dependent on them. Also - be sure to download your work (File | Download) so you have copies in case you don't have internet access or jsbin is inaccessible.



    Dynamically changing HTML with innerHTML

    Click the button to change the content of the area below without re-writing the whole page.

    This is a paragraph.

    Source code for above


    <script>
    var imgBase ="http://dotnet.tech.ubc.ca/hope/images/weather/";
    function drawPictures(){
    // we are writing an HTML statement that looks like this:
    // <img src="1s.gif" alt="">
    // to use document.write with double quotes it becomes like this:
    // "<img src=\"" + imgSrc  + "\" alt=\"" + imgSrc +"\" >"
    // could also have bee written like this using single quotes:
    // "<img src='" + imgSrc  + "' alt='" + imgSrc +"' >"
    var htmlForImages =""
    for (var i=1; i <= 44; i++) {
    				var imgFile = i + "s.gif" ;
    				var imgSrc=imgBase + imgFile  ;
     htmlForImages += ("<img src=\"" 
           + imgSrc + "\" alt=\"" + imgSrc +"\" >")	;
     }
    // update the HTML 
     document.getElementById("imageOutput").innerHTML=htmlForImages;
    // update the button (change what happens on click) and the text on the button
    // VERY long way to do this = document.getElementById("showMe").onclick=function onclick(event){showTime();};
    // Notice in line below - no parentheses after showTime
     document.getElementById("showMe").onclick=showTime;
     document.getElementById("showMe").value="show time";
    } 
    function showTime(){
     document.getElementById("imageOutput").innerHTML=Date();
    // update the button (change what happens on click) and the text on the button
    // VERY long way to do this =  document.getElementById("showMe").onclick=function onclick(event){drawPictures();};
    // Notice in line below - no parentheses after drawPictures
     document.getElementById("showMe").onclick=drawPictures;
     document.getElementById("showMe").value="show images";
    }
    </script>

    The html on which this relies


    <p id="imageOutput" style="height:100px">This is a paragraph.</p>
    <script type="text/javascript">
    document.getElementById("imageOutput").innerHTML=Date();
    </script>
     
     
    <form>
    <input id="showMe" type="button" value="show images" onclick="drawPictures()">
    </form>



    References

    Arrays

    A quick look at Arrays


    Review: Arrays

    Discuss Form Elements and Arrays

    Event Handlers and Anonymous Functions

    We will discuss this in class

    Event Handlers Inline, ById

    Live version of this discussion Event Handlers and Anonymous Functions


    Consider this form and notice the inline event handler onclick = "thankyou();"


    To separate the behaviour from the layout you would NOT use the inline event handler. Starting here's the HTML without it.


    Here is the approach using JavaScript to create event listeners.

    Cross Browser Issue

    Internet Explorer 8 and earlier used this form

    to write in a browser agnostic manner you could do this:

    A Quick Reminder About Arrays

    A quick look at Arrays


    Review: Arrays

    Discuss Form Elements and Arrays

    Event Handlers Inline, ById, ByTagName, ByClassName

    Live version of this discussion Event Handlers Inline, ById, ByTagName, ByClassName


    In this example we will attach event handlers Inline, ById, ByTagName, ByClassName.

    The HTML

    Here is the approach using JavaScript to create event listeners.

    The JavaScript


    And we need some CSS help to make this work.

    The Stylesheet

    CSS Selectors and JavaScript (and jQuery)

    We will start of with the three most common selectors that all us to find elements within the Document Object Model.

    CSS Selectors demo using JavaScript see it in jsbin

    CSS Selectors demo using jQuery see it in jsbin

    Related reading

    Event Logging with Firebug

    Here is how you can see events firing in your web pages. (click to view)


    In Firefox...

    Image:EventLoggingWithFirebug01.jpg


    Image:EventLoggingWithFirebug02.jpg


    And similar capabilities in other browsers.

    In most modern browsers you can access developer tools by pressing the F12 Key.


    Unobtrusive JavaScript

    While there are several aspects to the Principles of Unobtrusive JavaScript, we'll explore just one for now.

    Concept: Separating the JavaScript from the HTML

    The first three links will open in a popup window.
    Course Descriptions
    JavaScript description
    jQuery description
    UBC (not in a popup)


        <a href="/courses/" class="popup">Course Descriptions</a>
        <br />
        <a href="/courses/#ip356" class="popup">JavaScript description</a>
        <br />
        <a href="/courses/#ip250" class="popup">jQuery description</a>
        <br />
        <a href="http://ubc.ca" >UBC (not in a popup)</a>

    In JavaScript:

            window.onload = showlinks;
            function showlinks(){
     
                var elements = document.getElementsByClassName("popup"); // a custom function
                for (var i = 0 ; i < elements.length ; i++) {
                    elements[i].onclick = function () {
                        var myPopup=window.open(this.href, "popup", "status=1,scrollbars=1");
                        myPopup.focus();
                        return false;
                    }
                }
            }

    More on document.getElementsByClassName

    Examples

    Scope and Event Handling a quick demonstration.

    Session 3 Examples

    Assignment Three

    Comment in the Course Blog

    Session Three Notes

    Hands On

    You can use jsbin or similar tool to create and test your JavaScript but you must then make that code work in a page your_nameNN.html that is linked to your homepage on course ftp server. The objective is to ensure that you know how to work outside the jsbin environment.

    HINT: Download your work in jsbin (see: File | Download) and study where the JavaScript code resides in the document.
    Hint, Hint... Put your JavaScript at the bottom of your page so that the document is complete before you attempt to make references to IDs or TagNames or Classes.

    document.getElementById("")

    Consider this example that used document.getElementById : Simple Chalkboard example or Prettier Chalkboard example

    Create a page your_nameNN.html that writes content to ( sets the .innerHTML )

    <div id="javascriptOutput">

    You can make that as simple or challenging as you like.

    Simple: Write a string

    Challenging: Create a user input form and process the responses and then write to the <div>

    Event Handling

    Consider this example that used document.getElementById : Event Handlers Inline, ById, ByTagName, ByClassName

    Create another page your_nameNN.html that has at least two different event handlers.

    The event handlers must do something visible like change the .innerHTML of a div or change a style attribute. If you are familiar with CSS you can .addClass or .removeClass.

    Background Reading

    Catchup reading: Consolidation and review:

    Unobtrusive JavaScript


    Reading: JavaScript Events / Closures / Anonymous Functions

    These articles were in the session two assignment. If you haven't already read them please relax and read for light understanding

    PeerWise

    Create a new question by Tuesday night. Answer all unanswered questions by Wednesday before the next class. Please rate the questions as you do them.

    Session Four

    At the end of this session (and after completion of the session one assignment) you should be able to
    • Discuss the issues that come up when clients do not have JavaScript enabled.
    • Understand the window.onload and other events
    • Know where to find JavaScript reserved words
    • Use developer tools in various browsers
    • Use use strict
    • Identify JavaScript Core Objects
    • Use jQueryUI User Interface Interactions Accordion and Tabs

    Journal

    Next Steps

    HTML5 3: Building Dynamic Experiences with JavaScript Starts Tuesday November 24 - December 15, 2015, 06:30pm to 09:30pm, register by Monday November 23rd.
    jQuery: Beyond Fundamentals Starts Wednesday November 25 - December 16, 2015, 06:30pm to 09:30pm - please register by the Tuesday November 24th.

    • What are some of the disadvantages of document.write()?
    • What do you know about the Document Object Model

    To prepare for this session we will

    1. Review assignments - Group Discussion
    2. Homework assignments: Working in pairs, share your work.
      1. What worked?
      2. What didn't?
      3. What was the most challenging?

      1 Session Four
    Final Assignment

    optional NOTE: More information if you want to do some jQuery: You can use the Google libraries or the Microsoft ones. Both will work.


    jQuery on Google CDN (Content Delivery Network)

    Source: https://developers.google.com/speed/libraries/devguide#jquery

    jQuery on Microsoft CDN (Content Delivery Network)
    source: http://www.asp.net/ajaxlibrary/cdn.ashx

    Use jQuery UI in jsbin
    Image:jsbinAddjQueryUI.png


    Optional backup to load local copy
    As a backup option you can still host jQuery on your web server and only reference it if your visitor somehow fails to load the CDN hosted jQuery library.

    Add this method below your CDN jQuery reference. This code will check to see if jQuery is loaded and if it isn't the script will load the jQuery library from your web server. — source: Using a Content Delivery Network to Host jQuery

    If you have questions about JavaScript or this assignment - please post them in the course blog (Session One Notes). If you spot a question from someone else and you can answer it - please do.

    • Login in to PeerWise :IP356W12A
    • Create at least one new question.
    • Answer at least five questions.
      • Correct your answers if necessary.
        • Confirm your answers as you go along.
      • Help where you can to improve explanations.
      • Add comments in the questions.
      • Rate the questions.

    Detailed Instructions

    Reflect in the course blog


    Please click the picture above and answer the following questions in the course blog.

    Highlights / Metacognition
    • What did you think was the most valuable thing that happened for you tonight?
    • What did you learn from that?
    • What will you do with that knowledge?
    Questions?
    • Now that we've had our session together, what do you want to know?
    • What could we have done better?

    Course Blog Tutorial (video)

    External links / resources

    A little history


    No JavaScript?

    What - no JavaScript?



    What: No JavaScript?

    <head>
      <noscript>
        <meta http-equiv="refresh" content="0; url=http://myserver.com/pageToViewIfNoJavaScript.html" />
      </noscript>
     
      <script>
        location.replace('http://myserver.com/anotherPageWithJavaScript.html');
      </script>
    </head>


    window.onload and other events

    As we saw last week, if we use JavaScript to manipulate the Document Object Model, we must be sure that the document object model is complete before running the JavaScript.

    Live Example in jsbin

    window.onload and other events on the demo site

    Review - Writing to the Screen (Updating the Document Object Model)


    Reserved Words

    Developer Tools

    JavaScript

    Internet Explorer 9 and above
    F12 developer tools enables web developers to quickly debug JavaScript code without leaving the browser. Built into every installation of Windows Internet Explorer 9, F12 tools provides debugging tools such as breakpoints, watch and local variable viewing, and a console for messages and immediate code execution.

    Using the F12 Developer Tools to Debug JavaScript Errors.

    FireFox

    Articles


    Debugging Examples

    • Start Internet Explorer OR FireFox (after installing FireBug)
      • navigate to Output of a function updates .innerHTML
      • F12 for F12 Developer Tools OR Firebug
      • Set breakpoint at line 18
      • Watch msg (will show an error until running)
      • Run and examine msg
      • Add Watch document.getElementById("javascriptOutput").innerHTML
      • Run and examine - and note innerHTML

    Strict mode "use strict";

    This section is for discussion only. We won't be writing any code for this. We're just raising awareness of this feature that will be more relevant going forward.

    Use Strict details


    ECMAScript5's strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. Strict mode makes several changes to normal JavaScript semantics. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors. Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. Third, strict mode prohibits some syntax likely to be defined in future versions of ECMAScript. Strict Mode (Mozilla Developer Network)

    Things you can't do in strict mode. You can't:

    • Use undeclared variables (must use var. This means no more (accidental) implicit declarations)
    • Duplicate arguments in functions | function myFunction( name, address, name ) {}
    • Use future keywords (class enum export extends import super implements interface let package private protected public static yield)
    • Duplicate properties | var myCar = { make: "Ford" , model: "Fairlane", make: "500" };
    • Use of "eval" as identifier (see first link below)
    • Assignment to a non-writable property
    • Assignment to a non-extensible object
    • Delete undeletable property
    • Octal
    • "eval" variable introduction

    http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ (down to but not including discussion on JSON)

    http://caniuse.com/#feat=use-strict

    Article: Call JavaScript Functions without using eval.

    Simple version:

    You can limit strict mode to the contents of a function.

    You can wrap all of your JavaScript in a library inside a function to apply strict mode to your code only. This is less intrusive on other code or libraries that may not be using "use strict".

    Avoid Error Messages

    If you are using jsbin add this to the top of the JavaScript panel.


    Sample template for use with JS BIN

    String Manipulation

    Exploring the Predefined Core String Object - what can we do with it?]

    References:

    JavaScript String Object details

    Examples
    window.onload = function (){
    theOutput = document.getElementById("theOutput");
    theForm = document.getElementById("theForm");
    theButton = document.getElementById("theButton");
    theText = document.getElementById("theText");
    theText.placeholder = "Replace This With Something";  
    //theText.value = "SuperCaliFragiListicExpeAliDocious" ; 
     
    theButton.onclick= function(){
      // if there is nothing to process use the placeholder
      var textToProcess = theText.value ? 
          theText.value : theText.placeholder;
      //  call the function that does the work
      theOutput.innerHTML=flipTheCase1(textToProcess);
      // disable default for click so the form doesn't try to submit
        return false;
       };
     
    theForm.onsubmit = theButton.onclick; 
      // if the user hits Enter, then treat click the button for her
    };
     
    console.log(flipTheCase1("School is fun at UBC"));
    console.log(flipTheCase2("You can get any thing you want at Alice's Restaurant"));
    console.log(flipTheCase3("SuperCaliFragiListicExpeAliDocioust"));   
     
     
     
    // function to be called later
    function isLowerCase(characterToCheck){
      // return true if characterToCheck is lower case
      return characterToCheck==characterToCheck.toLowerCase();
    }
     
    function flipTheCase1(stringToFlip){
    var stringArray = stringToFlip.split(""); // create array 
    var stringOutput = "";  
    var character = "";
      // iterate over the characters
      for (var  i = 0; i < stringArray.length; i++) {
        character = stringArray[i];
        if (isLowerCase(character)) {
          character = character.toUpperCase();
        }
        else {
          character = character.toLowerCase();
        }
        stringOutput+= character;
       }
        return stringOutput;
    }
     
     
     
    function flipTheCase2(stringToFlip){
    var stringArray = stringToFlip.split(""); // create array 
    var stringOutput = "";  
    var character = "";
      for (var  i = 0; i < stringArray.length; i++) {
        character = stringArray[i];
     
    // use JavaScript Ternary operator instead of if()    
      stringOutput +=  (isLowerCase(character)) ? 
        character.toUpperCase() : character.toLowerCase();
        }
        return stringOutput;
       }
     
     
    function flipTheCase3(stringToFlip){
    var stringArray = stringToFlip.split(""); 
    var stringOutput = ""; 
     
    // use array.forEach
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
     
      stringArray.forEach(function(element, index, array) {
      stringOutput +=  (isLowerCase(element)) ? 
        element.toUpperCase() : element.toLowerCase();  
      });
       return stringOutput;
    }

    References:


    Date Calculations

    Review Dates & Arrays

    Discuss: Date Calculations

    Core (Intrinsic) Objects


    References

    Object Orientation in JavaScript

    Objects are a very convenient way to package data and functionality. You can also consider objects as way to create an associative array (data arranged as "name:value" pairs).

    Show/Hide the code

    Reference: Working with Objects — developer.mozilla.org

    jQuery Discussion

    Here is a super quick look at jQuery and JavaScript in jsbin.

    JavaScript


    jQuery


    jQuery on Content Delivery Networks

    Article: Using a content delivery network to host jQuery


    jQuery on Google CDN (Content Delivery Network)

    Source: https://developers.google.com/speed/libraries/devguide#jquery

    jQuery on Microsoft CDN (Content Delivery Network)
    source: http://www.asp.net/ajaxlibrary/cdn.ashx

    Use jQuery UI in jsbin
    Image:jsbinAddjQueryUI.png


    Optional backup to load local copy
    As a backup option you can still host jQuery on your web server and only reference it if your visitor somehow fails to load the CDN hosted jQuery library.

    Add this method below your CDN jQuery reference. This code will check to see if jQuery is loaded and if it isn't the script will load the jQuery library from your web server. — source: Using a Content Delivery Network to Host jQuery

    jQueryUI Tabs

    .tabs()

    jQueryUI Tabs
    A single content area with multiple panels, each associated with a header in a list. jQuery Tabs

    Note that in addition to jQuery, you need jQueryUI and the jquery-ui.css

    heightStyle controls the height of the tabs widget and each panel. Possible values:
    • "auto": All panels will be set to the height of the tallest panel.
    • "fill": Expand to the available height based on the tabs' parent height.
    • "content": Each panel will be only as tall as its content.
    Tabs Options


    jsbin jsbin version

    jsfiddle jsFiddle backup

    Another example with a different stylesheet

    jQuery

    CSS

    HTML



    jQueryUI Accordion

    .Accordion()

    This example is based on code found here http://jqueryui.com/accordion/

    Section 1

    Section 1 Content
    This is the jQuery Accordion Widget.
    See Section 3 to find out why this is so tall.
    Or we could have set the autoheight option to false $("#accordion").accordion({ autoHeight: false});

    Documentation: see the autoheight parameter
    Click the header "Section 1" to collapse the accordion and see the other sections.

    Section 2

    Section 2 Content
    Use this when you have multiple sections and want only one visible at a time.

    In this example you can close all the sections because the collapsible option is set to true

    $("#accordion").accordion({ collapsible: true });

    Try it. Click the bar above that says "Section 2"

    Section 3

    Section 3 Content
    Use caution - and notice that if you have really long content it may be difficult to see the accordion section links. And the longest section sets the height for all of the sections.

    http://huwshimi.com/comic/

    Section 4

    Section 4 Content
    Thanks for reading all four sections.


    jsbin version

    jsFiddle version

    Another example with a different stylesheet

    Two Accordions on the same page

    jQuery

    CSS

    HTML



    Final Assignment

    Final Assignment

    optional NOTE: More information if you want to do some jQuery: You can use the Google libraries or the Microsoft ones. Both will work.


    jQuery on Google CDN (Content Delivery Network)

    Source: https://developers.google.com/speed/libraries/devguide#jquery

    jQuery on Microsoft CDN (Content Delivery Network)
    source: http://www.asp.net/ajaxlibrary/cdn.ashx

    Use jQuery UI in jsbin
    Image:jsbinAddjQueryUI.png


    Optional backup to load local copy
    As a backup option you can still host jQuery on your web server and only reference it if your visitor somehow fails to load the CDN hosted jQuery library.

    Add this method below your CDN jQuery reference. This code will check to see if jQuery is loaded and if it isn't the script will load the jQuery library from your web server. — source: Using a Content Delivery Network to Host jQuery


    Recommended Resources



    Additional Exploration

    TypeScript

    TypeScript is a language for application-scale JavaScript development.

    TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

    Any browser. Any host. Any OS. Open Source.

    Typescript

    s Microsoft's TypeScript Programming Language Worth the Fuss?

    Assignments

    Assignment 1

    To be completed before Monday March 5, 2012

    Reading

    Review and consolidate concepts:
    JavaScript Overview
    Preparation for next session:
    JavaScript Guide: Grammar and Types

    Update Your Pages
    1. Change the Descriptions for the files we created in the first session, so that those descriptions are meaningful to you.
    2. Use WebMatrix, Visual Studio, or FTP to upload your homepage and page 01 to the UBC Server


    WebMatrix (Windows Clients only)

    WebMatrix is the editor/ftp client that we are using in the lab. Download it here: WebMatrix

    Note: Once you have your site created (what we are doing here), you can then access it from "My Sites" above.


    WebMatrix Publish Settings
    1. Download
    2. Double-click the file and extract (drag) the contents to the desktop
    3. Start WebMatrix
    4. Click Open
    5. Click Remote
    6. Import Publish Profile
    7. Navigate to the desktop and double-click ip356.azurewebsites.net.publishsettings
    8. voilà

    OR

    FTP Method
    1. Use an ftp client (e.g. Filezilla) to download your homepage from
      http://ip356.azurewebsites.net


    ftp host name: ftp://waws-prod-bay-001.ftp.azurewebsites.windows.net

    site path: site/wwwroot

    user name: ip356\ip491

    destination url: http://ip356.azurewebsites.net


    Thank you Adam for providing these screen shots of his FileZilla settings.

    Image:FileZillaIP356F15A1.png

    Image:FileZillaIP356F15A2.png

    Image:FileZillaIP356F15A3.png




    Assignment 2

    To be completed before Monday March 12, 2012

    Build your own version of Switch - call it your_name03.html

    Reading

    Consolidation and review:

    Reading ahead:


    Writing Pages
    • Switch: Build your own version of Switch - call it your_name03.html
    • Complete the assignments we started in class - see your html pages for instructions that you wrote. This can include migrating things we did in jsbin into full web pages (e.g. your_name04.html
    Optional
    • Function: Create a page your_name05.html so that it accepts user input for one or two parameters in a function that you create. You don't HAVE to create a user interface for the user to provide the parameters, but if you want to, create a form and allow the user to provide data that you use in the function.

    What the function does is completely up to you. But the outcome should be visible in the page (probably with window.alert()). If you can't think of a reason to build web page with a function, try figuring out a dog's age in dog years.

    You may use any of these Session 2 Models for ideas.

    Add a reference to this page in your 00.html table of contents too.

    Save the page as your firstName_yourlastName05.html and use FTP or WebMatrix to publish it to the student work site.

    Dog Years Algorithm

    If you can't think of a function you can try this something based on this:


    Formula for dogs less than 20lbs is y=4.1464x + 14.429
    Dogs 20-50lbs is y= 4.6107x + 14.111
    Dogs 50-90lbs is y= 5.457x + 11.61
    And, finally... Dogs 90 lbs plus is: y = 7.325x + 5.2667


    Reading Ahead
    JavaScript Events / Closures / Anonymous Functions

    Please relax and read for light understanding


    Assignment 3

    To be completed before Monday March 19, 2012 (your part, then add comments)


    Comment in the Course Blog

    Session Three Notes

    Hands On

    You can use jsbin or similar tool to create and test your JavaScript but you must then make that code work in a page your_nameNN.html that is linked to your homepage on course ftp server. The objective is to ensure that you know how to work outside the jsbin environment.

    HINT: Download your work in jsbin (see: File | Download) and study where the JavaScript code resides in the document.
    Hint, Hint... Put your JavaScript at the bottom of your page so that the document is complete before you attempt to make references to IDs or TagNames or Classes.

    document.getElementById("")

    Consider this example that used document.getElementById : Simple Chalkboard example or Prettier Chalkboard example

    Create a page your_nameNN.html that writes content to ( sets the .innerHTML )

    <div id="javascriptOutput">

    You can make that as simple or challenging as you like.

    Simple: Write a string

    Challenging: Create a user input form and process the responses and then write to the <div>

    Event Handling

    Consider this example that used document.getElementById : Event Handlers Inline, ById, ByTagName, ByClassName

    Create another page your_nameNN.html that has at least two different event handlers.

    The event handlers must do something visible like change the .innerHTML of a div or change a style attribute. If you are familiar with CSS you can .addClass or .removeClass.

    Background Reading

    Catchup reading: Consolidation and review:

    Unobtrusive JavaScript


    Reading: JavaScript Events / Closures / Anonymous Functions

    These articles were in the session two assignment. If you haven't already read them please relax and read for light understanding

    PeerWise

    Create a new question by Tuesday night. Answer all unanswered questions by Wednesday before the next class. Please rate the questions as you do them.


    Assignment 4

    Course Evaluation Form

    Final Assignment To be completed before Monday March 26, 2012

    Final Assignment

    optional NOTE: More information if you want to do some jQuery: You can use the Google libraries or the Microsoft ones. Both will work.


    jQuery on Google CDN (Content Delivery Network)

    Source: https://developers.google.com/speed/libraries/devguide#jquery

    jQuery on Microsoft CDN (Content Delivery Network)
    source: http://www.asp.net/ajaxlibrary/cdn.ashx

    Use jQuery UI in jsbin
    Image:jsbinAddjQueryUI.png


    Optional backup to load local copy
    As a backup option you can still host jQuery on your web server and only reference it if your visitor somehow fails to load the CDN hosted jQuery library.

    Add this method below your CDN jQuery reference. This code will check to see if jQuery is loaded and if it isn't the script will load the jQuery library from your web server. — source: Using a Content Delivery Network to Host jQuery

    Final Assignment


    Tools

    Modernizr Modernizr is an open-source JavaScript library that helps you build the next generation of HTML5 and CSS3-powered websites.

    Related Downloads

    Downloads




    MindMaps Optional

    You have a hard copy of the MindMaps in your notes.

    • Optional: View MindMaps on your computer
      • This is optional but not required to complete your course. I won't be able to provide support for this optional capability.
      • Note you will need to run Internet Explorer to do this.
      • I have also successfully used Firefox addin IE Tab.
    1. To view the MindMaps online please download
      MindManager Browser PlugIn
    2. To view the MindMaps offline please download
      MindManager Viewer 7

    If you download the maps, please put them all in single folder. You may have some issues with links from one map to another on your computer, but you should still be able to bring them up one at a time individually from this site.

    [[Category:IP356]]




Views
Personal tools
Navigation
Toolbox