JavaScript Essentials

3-day Basic JavaScript Web Design Course — JS-01

JavaScript Web Design TrainingCourse Overview

This basic JavaScript training course for beginners, is designed to get non-programmers started in JavaScript programming and web application development. The course is particularly suitable for front-end web designers who want to automate and animate interaction with end-users, but have no previous programming experience.

This JavaScript training course is designed to teach all of the fundamentals of JavaScript programming, i.e. the core language plus the techniques and add-on libraries which JavaScript programmers use on an everyday basis to accomplish the most common web design tasks.

No short training course is going to turn you into an expert programmer overnight. You'll need some aptitude for technical problem-solving, lots of post-course practice, and the ability to learn from your inevitable mistakes. This JavaScript course should, however, provide an excellent platform for doing those things and reaching that status.

JavaScript Web Design TrainingCourse Contents

Introduction to JavaScript

  • JavaScript & web programming
  • Outline/schedule of upcoming content
  • Prerequisite reminder: HTML, CSS
  • Not assumed: programming skills
  • Exercise prep: kit, apps, data, code
  • Relationship between JS, HTML, CSS
  • JavaScript: web-focus, browser-bound
  • Security: access files, DBs, hardware
  • Client-side vs. server-side PHP, etc.
  • Server-side JavaScript: other courses
  • Graceful degradation: essential
  • Browser compatibility: improving
  • ECMAScript v.5 the de facto standard
  • Tools: text editor & browser
  • Reference guide: mozilla.org
  • 1st JavaScript program: hello world
  • JavaScript editors survey
  • Browsers: any, but FF debugging
  • Firebug: install and use
  • Firebug console panel: basic use

Core JavaScript

  • Some basic foundations:
    • JavaScript is interpreted
    • Forgiving interpreters: not good
    • Case sensitivity
    • Statements: separate instructions
    • Code lines: semi-colon terminator
    • Parentheses, braces, brackets
    • Comments and whitespace
    • Execution order and HTML order
    • Inline JavaScript vs. separate file
    • Position of the script tag in HTML
    • Weakly v. dynamically typed
  • Variables: create, initialise, assign
  • Basic control structures
    • Setting conditions: if statements
    • Nesting conditions: else
    • Conditional operators
    • Arithmetic, boolean, increment
    • Operator precedence
    • Prefix and postfix operators
    • Debugging in Firebug console
    • .log, .debug, .info
    • .warn, .error
    • Loops: while, dowhile, for
    • Conditions, break, continue
  • Functions: group, separate, name
    • Function names
    • Calling functions
    • Where to declare functions
    • Function parameters
    • Function return values
    • Extra or missing parameters
    • Variable Scoping

JavaScript data types

  • Arrays
    • What is an array?
    • Why they matter
    • Manipulating groups of HTML tags
    • The array index
    • Zero-based array indices
    • Arrays are dynamic
    • Arrays are ‘objects’
    • Array properties: .length
    • Methods: .reverse, .join, .sort
    • Getting arrays from HTML/DOM
    • document.getElementsByTagName
  • Numbers
    • 64-bit floating point internally
    • With or without decimal points
    • Addition vs. concatenation
    • Depending on type
    • Combining numbers and strings
    • NaN — not a number
    • Converting strings to numbers
    • The isNaN built-in function
    • The Math Object
    • .max, .min, .round, .random, etc.
  • Strings
    • Creating string variables
    • Quoting strings
    • Quotes in quotes
    • Escaping quotes
    • Strings are objects
    • String properties e.g. .length
    • String methods — e.g. .toUpperCase, .toLowerCase, .split, .indexOf, .lastIndexOf, .slice
    • Comparing strings: sort order, case
  • Dates
    • The built-in Date function
    • Date get methods
    • .getMonth, .getFullYear, .getDate, .getDay, .getHours, .getTime
    • Date set methods
    • .setMonth, .setFullYear, .setDate, .setDay. .setHours, .setTime
    • Date comparison — using the .getTime method
  • Objects
    • JavaScript objects are quite limited
    • No formal classes
    • Containers holding data & behaviour
    • I.e. variables plus functions
    • Property: an object's variable
    • Method: an object's function
    • Create objects: new Object();
    • Create properties
    • I.e. associate variables with {}
    • Create methods
    • I.e. associate method with object

JavaScript and the DOM

  • What is the ‘model’?
  • An abstract description of:
    • All bits of a web page: at any level
    • The relationships between them
  • Naming convention JavaScript uses to:
    • Access page components
    • Control and modify them
  • What are the ‘objects?’
    • Page components at any level
  • Main types of objects:
    • HTML elements
    • Text
    • Lists of nodes, e.g. children
  • Each specific object is a node, e.g.
    • One element node
    • One attribute node
    • One text node
  • Relationships between nodes
    • Parents, grand parents, great …
    • Children, grand children, great …
    • Siblings: 1st, 2nd 3rd, last, next …
  • Stuff JavaScript can do with the DOM:
    • Find textual content
    • Insert/delete elements and attributes
    • Change content: URLs, metadata
  • Gotcha: text sits in text nodes

Using the DOM in JavaScript

  • document.getElementById
  • Get an array of elements by type
  • document.getElementsByTagName
  • Get properties of an element
    • Element type .nodeType
    • Element content .innerHTML
    • Element length .length
  • Get properties of an array of elements
    • E.g. no. elements of type .length
  • Get elements in one part of doc
    • document.getElementById
    • To select the container
    • .getElementsByTagName
    • To select descendants
  • Simple content editing
    • Change element attributes — .getAttribute() and .setAttribute()
    • Change content of standalone elements — .innerHTML()
  • Create/edit after current content
    1. .createElement, .appendChild, .createTextNode, .appendChild
  • Create/edit before current content
    1. .createElement, .getElementsByTagName, .insertBefore

JavaScript Events

  • What is an event?
  • Examples of events:
    • Page loading
    • User key press
    • User clicks
    • Screen scrolling
    • Enter a form field
  • Examples of JavaScript event names
    • onload, onfocus, onclick, onmouseover
  • What are event handlers?
    • Functions that do something in response to an event
  • 3 ways to add event handlers
    • In HTML attributes, usually bad
    • As an anonymous function document.onclick = function(){};
    • The .addEventListener method
  • IE<9 gotcha: uses .attachEvent instead of .addEventListener
    • jQuery cross-browser handlers
    • Detect which functions exist
    • ‘Translates’ non-standard stuff e.g. .attachEvent
    • Don't write custom detection code
  • Handling load and click events
    • Inline e.g. alert on button click
    • Ensure doc is loaded window.onload = function(){}
    • Enlarge an image onclick
  • Handling focus and blur events
    • Delete placeholders: onfocus
    • Restore when leaving: onblur
  • Using timers (not strictly events)
    • setTimeout, setInterval, clearTimeout, clearIntervali

JavaScript Debugging

  • Takes more time than coding
  • Browsers ignore many errors
  • So use a debugger
  • JS consoles will find syntax errors:
    • Don’t show every ‘mistake’
    • E.g. unintended output
    • Show line where error is detected
    • May actually occur previously
    • Describe error types
    • Not always intuitively
  • Common errors
    • Poor termination, e.g. braces, parentheses, quotes, semi-colons
    • Calling functions that don’t exist
    • Case-sensitivity and typo errors
    • Variable hasn’t been created yet
    • Assignment, equality, identity
    • Surprising but correct results, e.g. NaN from undefined variables
  • Using Firebug
    • Modes: console, HTML, CSS, Script, DOM, Net
    • Navigate from an HTML element to it’s DOM nodes, CSS etc.
    • Shows nodes/HTML created/edited by JavaScript after page load
    • Script mode: see all JavaScrit
    • Use Script mode of debugging
    • Step through lines and break points
  • Example debugging session in Firebug
    • Finding logic errors
    • Using Firebug’s Script mode
    • Set break points
    • Run the code
    • Step through controls
    • Continue, step-into,-over,-out
    • Step-into: code logic vs. line order
    • Viewing the watch window
    • Showing values of local variables
    • Step-out of a loop
    • Go 1 level back up the logic
    • Step-over a loop
    • Execute, then move to next step
    • Conditional break points
    • Only stop if a variable is true

JavaScript for richer forms

  • Field values, field events, form events
  • An alternative to .getElementById
  • document.forms.name
    • For named fields
  • The key textfield property is .value
  • Main textfield events
    • onfocus, onblur, onchange, onkeypress, onkeydown, onkeyup
  • Checkbox & radio button property: .checked
  • Checkbox and radio button events:
    • onclick, onchange
  • 3 select list properties:
    • .type, .selectedIndex, .options[].selected
  • Key select list event: onchange
  • The whole form event: submit
    • Interrupt submission by return false
    • For client-side validation
    • Back-up with server-side
  • Example: client-side form validation
    • Require an email address
    • Add error message if rejected
    • Reject further incomplete submits
    • Allow correct submission
    • Generate success message
  • Example: event on single form control
    • Show/hide form section
    • In response to branching question
    • Test branching question is checked
    • If checked, show the section
    • Using .style.display = "block"
    • If unchecked, hide the section
    • Using .style.display = "none"
    • Hide on initial page load
    • Section is always visible ...
    • If JavaScript is disabled/missing
    • Progressive enhancement

JS for dynamic styling

  • Change CSS dynamically, like HTML
  • Example: changing inline styles:
    • .getElementById then set .style
    • CSS names for 1-word properties
      • .style.color
      • .style.border
    • Multi-word use camelCase, e.g.
      • .style.backgroundImage
  • Hyphenated properties also camelCased
    • Because hyphen/minus is the JavaScript subtraction operator
  • Avoid CSS semi-colons
    • The JavaScript statement terminator
  • .className styles HTML classes
    • Not .class — a JavaScript keyword
  • Example of styling a class:
    • Select an element when it’s clicked .getElementById(myElementId).onclick
    • Check class name is set in CSS .getElementById(myElementId) .className == "myClassName"
    • If true, blank it .getElementById(myElementId) .className = ""
    • If false, set it .getElementById(myElementId) .className == "myClassName"
    • Class style toggles when clicked
  • N.B. CSS specificity still applies
    • Most specific always ‘wins’
  • Changing styles to animate:
    • Select the element
    • setTimeout(beginAnimate,1000) starts, then terminates after 1 sec
    • Get element and set its position .style.position = "absolute"
    • Call setInterval() to set frequency of movement
    • Create a function to increment current CSS position after each interval
    • Set the object’s final position, putting a max. offset condition on the function

Best Practices in JavaScript

  • How you should/not write JavaScript
  • Typical issues in JavaScript coding style:
    • Variable names
    • Function names
    • Positioning braces
    • Positioning functions
  • Objectives for JavaScript coding style:
    • Readability — with clear meanings
    • Consistency
    • Accepted/conventional practice
  • Why coding style matters in JavaScript
    • No hiding behind a compiler
  • Naming variables and functions:
    • Avoid placeholders — e.g. foo, bar
    • CamelCase — often verb-noun format
  • Naming objects:
    • Capitalise the first word
    • Single words more common
  • CamelCase is standard for JavaScript
    • Yahoo, Google, jQuery style guides
    • Used in DOM methods
    • But other language styles are allowed
  • Brace style convention:
    • Open at the end of the first line
    • else same line as closing if brace
    • Other styles can cause problems
    • E.g. interpreter wants to insert missing semi-colons
  • Always use semi-colons
  • Always use braces — even for one-liners
    • To accommodate later changes
  • Define functions before you call them
  • Always use var declare variables
  • Look up the Yahoo, Google and Mozilla JavaScript style guidelines
  • Compacting code — minification
    • Remove comments
    • Rename long var and function names
    • Remove whitespace and line breaks
    • Only done to speed download
    • Is not ‘compiling’
    • Not intended to obfuscate
    • Done programmatically
  • Minification tools
    • JSMin
    • Yahoo Compressor
    • Google Closure Compressor
  • Walk through Google’s Closure
    • From appspot.com
    • Simple and advanced options
    • Detects potential gotchas
    • Copy and paste or download output
  • Using minified code
    • Always keep the original — editable
    • Minified JS libraries, e.g. jQuery
  • Code quality checkers — JSLint
    • http://jslint.com
    • By Douglas Crockford, Yahoo
    • IDs all common quality problems
    • Warnings on bad, but do-able, stuff
    • But is designed to be very picky
    • 100s of warnings on working code
    • E.g. calling functions before declaring
    • E.g. Using variables before defining
    • Warns on poor indentation, spacing
    • Worth stepping through line by line
    • Watch out for ECMAScript 5 warnings
    • With/without i"use strict";
    • Many options to tolerate bad stuff
    • Many options to assume, e.g. browser

Useful JavaScript Libraries

  • What are JavaScript libraries?
    • Bundles of ready-to-use JS code
    • Thousands of them — mostly FLOSS
  • Knowing and using them is a core skill
  • General-purpose JavaScript libraries:
    • E.g. Closure, MooTools, Dojo, jQuery
    • DOM traversal, cross-browser compatibility, AJAX server integration
  • Specialised JavaScript libraries
    • E.g. CurvyCorners, script.aculo.us
  • Linking to multiple JavaScript files
    • Library use makes this common
    • Link order really matters
    • Every link: a HTTP request, download, processing
    • Sequential: previous must complete
    • Combine in 1 file — whenever possible
    • Load files after their dependencies
    • If you need functions immediately ...
    • Link in the HTML <head>
  • jQuery: the top general-purpose library
    • Makes JavaScript much much easier
    • E.g. DOM traversal, cross-browser code, event handling, AJAX, etc
    • Download from jquery.com
    • Development version, easily editable
    • Production version, minified
    • Terser code for core JavaScript
    • Extract content more easily, e.g.
      • All the elements in a class
      • All the elements of a given type
      • All the elements in given positions
      • Using CSS-style selectors
      • Selectors and be combined like CSS
      • Pseudo-class selectors like CSS
    • Key feature: add classes to any selectable page component
      • HTML class/ID need not to exist
      • Functions like static class
  • Examples of using jQuery in practice
    • Adding a class to the DOM
    • Find elements in a given class
    • Find elements of a given type
    • Find the last item in a list
    • Find intro para in any section
    • Find headings containing a word
    • Hide a certain columns in a table
  • jQuery methods
    • jQuery("aSelector").anAction
    • .addClass adds, doesn't overwrite
    • .removeClass clear classes
    • .toggleClass add or remove
  • The jQuery alias, dollar sign
    • A terse var name pointing to jQuery
    • $("mySelector") .myAction(myParams)
  • jQuery simplifies syntax, e.g.
    • hide, show, slidedown, slideup, fadeout, fadein
  • jQuery simplifies event handling
    • Easy syntax
    • Remember event states, using this
    • Check dependencies met (.ready)
  • Using a CDN
    • Don't download/serve libraries
    • Link to jQuery at MS and Google
    • Faster and more reliable
    • Parallel downloads
    • Cached in user’s browser
    • Free and easy to do
    • developers.google.com/speed/libraries/
    • Details libraries supported
    • No need for API key or loader script
    • Just find URL for the library you want
    • HTTP and HTTPS URLs
    • Both using scheme-less URLs

JavaScript and HTML5

  • HTML5 adds lots of new features
    • Built in video, audio, geolocation, local storage, offline storage, drag and drop, canvas
    • Previously only available via plugins
    • New semantic markup + metadata
    • New elements and syntax for forms
    • New JavaScript APIs to control behaviour of the new features
  • Press/PR coverage often conflates it with CSS3 and JavaScript features
  • Little change in HTML,CSS,JS usage:
    • HTML5 — content
    • CSS3 — presentation
    • JavaScript — behaviour
  • Not finished, but:
  • JavaScript additions in HTML5
    • Only 1 general-purpose addition: .getEleentsByClassName
    • Been in jQuery for years
    • So IEs<9 are covered
    • Specialist additions for new features
  • HTML5 Video
    • Call methods .play() .pause()
    • Set properties .currentTime
    • Events controllable by .addEventListner()
      • play, pause, ended
  • HTML5 Storage
    • Simple: localStorage[]
    • More sophisticated:
      • Offline Storage, IndexDB
  • Web Workers
    • Load JavaScript, run in background
    • Allows multi-threading, not in IE9
    • var myWorker = new Worker("myScript.js");
    • Can’t affect the DOM
    • Can generate and send back events
    • Process messages from a worker worker.onmessage = function(){};
    • Send messages to a worker worker.postMessage(myfunction);
  • HTML feature detection
    • Treat as an object, ask if it exists if (document.myObjectName) {} else {}
    • Just use the Modernizr library
  • The Modernizr library
    • Checks current browser’s support
    • For every HTML5 and CSS3 feature
    • Can load shims+polyfills for old IEs
    • Link must be in HTML head
    • Creates JS object with 40+ properties Modernizr.video, Modernizr.canvas
    • Returns true or false browser support
      • Per given property
    • if (Modernizr.video) 
      {// use HTML5 video} 
      else 
      {// use Flash}
    • Modernizr custom builder
    • Only check for features you need
    • Available on MS CDN: www.asp.net/ajaxlibrary/cdn.ashx

Advanced JavaScript Features

  • Strict mode
    • An ECMAScript 5 — but handy for use with advanced and bleeding edge JavaScript
    • Force yourself to use higher standards
    • Get more out of checkers like JSLint
    • Browsers that support it will stop:
      • If you don’t declare variables with var before use
      • If you use duplicate parameter names
      • … etc.
    • Only useful if you test pages in browsers with support
    • Just add "use strict";
      • At the top of your file — to control the whole thing
      • At the top of a function — to control just that function
      • Non-supporting browsers — just ignore it as a string literal
    • Be consistent — all .js files in a page strict, or none
    • If you must mix — put a blank function wrapper around content in each strict file
      • Clunky workaround suggested by JSLint
  • JavaScript Bad Practices — stuff you shouldn’t copy
    • There’s lots of this about
    • document.write
      • Writes a string to current page — including markup
      • Doesn’t work in XHTML
      • Broken understanding of the DOM
      • Only works during initial page load
      • If run after page load — wipes out all content
      • Use innerHTML or manipulate the DOM instead
    • Browser sniffing — by .userAgent or .appName
      • Ancient bad practice — was always wrong
      • Should detect features/objects — not browsers
    • Eval
      • Really dangerous — executing variables which could come from elsewhere
      • There are always better ways to do the same thing
    • <a href="javascript:myFunction">
      • Utterly useless when JavaScript is disabled
      • Mixes behaviour with content
      • A pseudo-protocol
    • <a href="myPage.html" onclick="myFunction(); return false;">
      • Another pseudo-protocol
      • Does at least treat the ink as a real link
      • Only calls function if JS enabled
      • Defaulting to standard link if no JS
      • Still mixes behaviour with content — put event handlers in separate code
  • Regular expressions
    • Pattern matching strings
    • Handy for:
      • Checking inputs match a pattern e.g. phone numbers, postcodes
      • Finding substrings
    • To create a regular expression:
      • Assign the expression to a variable — myRgx = /Foo/
      • Create a variable holding the text to search through — var myText = "Foo bar baz"
      • Check whether a match occurs — if (myRgx.test(myText)) {// do something}
      • Find ou where the first match occurs — if (myRgx.search(myText)) {// do something}
    • More complex pattern matches using special characters
      • ^ at the start
      • $ at the end
      • + once or more
      • * zero or more
      • ? zero or one
      • | either|or
      • . any character
      • \w alphanumeric or underscore
      • \b word boundary
      • [] range of characters
    • Examples of complex patterns using special characters
  • AJAX
    • Misleading buzzword acronym — Asynchronous JavaScript and XML
    • Not much to do with XML
    • Just JavaScript — updating bits of pages by communicating with the server
    • Much faster than server-side only web apps
    • E.g. Google maps scroll and zoom
    • Two-part process in JavaScript:
      • Create a request to the server
      • Process responses from the server
    • Asynchronous — the two processes are separate
      • Other page processes continue — unfulfilled requests don’t block
    • 3 steps to make the request:
      • Create a request — var myRequest = new XMLHttpRequest();
      • Configure a http request to server-side script — myRequest.open("GET", "http://example.com/script.pl", "true");
      • Send the request — myRequest.send(null);
    • Steps to handle the response:
      • Create an event handler for the response — myRequest.onreadystatechange = function() {};
      • Configure a http request for the response — myRequest.open("GET", "http://example.com/script.pl", "true");
      • Send the request for the response — myRequest.send(null);
      • Do something with the returned data — e.g. put it into a new DOM node
    • N.B. .onreadystatechange polls repeatedly until certain the response is ready
      • So you may see the data several times in the console
    • MS has a proprietary name and syntax for XMLHttpRequest
      • Let jQuery take care of the difference
      • Don’t bother with your own object detection
  • Prototypes
    • What is a prototype?
      • A way of ‘faking’ OO classes in JavaScript
      • I.e. create formalised objects — that can share properties and methods
    • Creating a prototype
      • Create a constructor object
        • function Myconstructor(param1, param2, param3) {// assign values to instances of the parameters}
        • Upper case first letter in its name — it’s an object
      • Create a new object from the constructor function:
        • var foo = new Myfunction("Foo");
        • foo is the object and Foo is a property of it
      • Create further new objects from the constructor function
        • var bar = new Myfunction("Bar")
        • var baz = new Myfunction("Baz")
      • Attach new functions to the constructor — using the prototype property:
        • Myconstructor.protype.firstNewMethod = {// do something}
        • Myconstructor.protype.secondNewMethod = {// do something}
      • Call the new methods on the properties of foo, bar, baz or any further objects created from the constructor:
        • foo.firstNewMethod();
        • foo.secondNewMethod();
        • oof.firstNewMethod();
        • oof.secondNewMethod();

Conclusion — Fitting the Bits Together

  • 3 worked examples of using several different techniques together. e.g.
    • Create DOM elements
    • Respond to events
    • Error check form input
    • Use timing and set intervals
    • Hide and show page components
    • Use built-in objects to calculate numbers, dates, times etc
    • Select and change elements
  • Examples:
    • Design a booking form
    • Automatically re-design layout for different media
    • Use a third-party library to enhance the form and layout, e.g. use a custom build of jQuery UI to add interactions, widgets and effects
  • Web and other resources — for problem solving, learning and improving
    • Beware of search engines — average JavaScript advice is lousy
    • Lots long-deprecated, extremely dated
    • Bad signs — techniques described in our bad practices section, e.g. document.write
    • Recommended sites — in rough order of precedence:

JavaScript Web Design TrainingCourse Schedule

JavaScript Web Design TrainingFurther Details

Course Objectives

On completion of this JavaScript training course, you should be able to:

  • Understand the basic principles of computer programming
  • Appreciate which web design tasks are suited to JavaScript solutions — and which are not
  • Know and use core JavaScript syntax and functions
  • Select and use popular JavaScript libraries, e.g. jQuery
  • Understand and manipulate the Document Object Model using JavaScript
  • Write event-handling JavaScript routines, from scratch
  • Debug and test scripts and script-dependent web pages
  • Use JavaScript to enhance web form usability and appeal
  • Understand and use JavaScript programming best practices
  • Understand a range of useful advanced JavaScript programming techniques
  • Know where to learn and how to practice more advanced JavaScript techniques

Target Audience

  • Experienced CSS-based web designers

Private group versions of this course are quite suitable for experienced programmers, but individual programmers should not book themselves on public versions of the course, unless they:

  1. Are comfortable in mixed groups — with non-programmers
  2. Have the pre-requisite HTML and CSS experience

Training Pre-requisites

Successful completion of the following 1-day training courses, or equivalent knowledge and experience:

The material in those courses is also covered in these 2-day courses, respectively:

Training Style

This JavaScript training course, is instructor-led, hands-on practical training.

Hands-on practical work will comprise between 40% and 60% of the contact time, depending on the needs of the particular training group.