JavaScript Essentials
3-day Basic JavaScript Web Design Course — JSE
JavaScript Training Course 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.
Course contents — 1 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
Course contents — 2 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 Firefox console
.log
,.debug
,.info
.warn
, .error
- Loops:
while
,do
…while
,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
Course contents — 3 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
Course contents — 4 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
Course contents — 5 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
- Element type
- Get properties of an array of elements
- E.g. no. elements of type
.length
- E.g. no. elements of type
- 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
.createElement,
.appendChild,
.createTextNode,
.appendChild
- Create/edit before current content
.createElement,
.getElementsByTagName,
.insertBefore
Course contents — 6 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
- Delete placeholders:
- Using timers (not strictly events)
setTimeout
,setInterval
,clearTimeout
,clearIntervali
Course contents — 7 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 Firefox console
- Example debugging session in Firefox console
- Finding logic errors
- 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
Course contents — 8 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
Course contents — 9 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
- .getElementById then set
- 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
- Not
- 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
- Select an element when it’s 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
Course contents — 10 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 closingif
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, whitespace, linebreaks
- Rename long var and function names
- Do not obfuscate
- Do it 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
Course contents — 11 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
Course contents — 12 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:
- Most supported by current browsers
- Very backwards compatible
- Old IEs have ‘issues’
- Much fixable by jQ+Modernizr
- Compare layout engines (HTML5)
- caniuse.com
- 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
- Only 1 general-purpose addition:
- HTML5 Video
- Call methods
.play()
.pause()
- Set properties
.currentTime
- Events controllable by
.addEventListner()
play
,pause
,ended
- Call methods
- HTML5 Storage
- Simple:
localStorage[]
- More sophisticated:
- Offline Storage, IndexDB
- Simple:
- 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
- Treat as an object, ask if it exists
- 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
Course contents — 13 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
- AJAX
- Prototypes
Course contents — 14 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:
- developer.mozilla.org — they invented it
- dev.opera.com — the browser innovator, usually first with new HTML, CSS and JS features
- stackoverflow.com — Q&As, first answer not necessarily best, check votes
Dates for Online courses
Dates for London
- Monday 9 Dec 2024 Barbican £1080 Book
- Monday 6 Jan 2025 Barbican £1080 Book
- Monday 3 Feb 2025 Barbican £1080 Book
Dates for Manchester
- Monday 9 Dec 2024 Albert Square £1080 Book
- Monday 6 Jan 2025 Albert Square £1080 Book
- Monday 3 Feb 2025 Albert Square £1080 Book
Dates for Leeds
- Monday 9 Dec 2024 Radisson £1080 Book
- Monday 6 Jan 2025 Radisson £1080 Book
- Monday 3 Feb 2025 Radisson £1080 Book
Dates for Glasgow
- Monday 10 Mar 2025 Ingram St. £1080 Book
- Monday 28 Apr 2025 Ingram St. £1080 Book
- Monday 19 May 2025 Ingram St. £1080 Book
Dates for Birmingham
- Monday 3 Feb 2025 Somerset House £1080 Book
- Monday 10 Mar 2025 Somerset House £1080 Book
- Monday 28 Apr 2025 Somerset House £1080 Book
Dates for Edinburgh
- Monday 3 Feb 2025 St Andrew Square £1080 Book
- Monday 10 Mar 2025 St Andrew Square £1080 Book
- Monday 28 Apr 2025 St Andrew Square £1080 Book
Dates for Newcastle
- Monday 10 Mar 2025 Clavering Hse £1080 Book
- Monday 28 Apr 2025 Clavering Hse £1080 Book
- Monday 19 May 2025 Clavering Hse £1080 Book
Dates for Bristol
- Monday 10 Mar 2025 The Waterfront £1080 Book
- Monday 28 Apr 2025 The Waterfront £1080 Book
- Monday 19 May 2025 The Waterfront £1080 Book
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:
- Are comfortable in mixed groups — with non-programmers
- 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.