Jessica’s Javascript Notes

Javascript Basics

  • Functions:
    • Named: function foo() { … }
    • Anonymous: function (){ … } – usually used on the right hand side of an equals sign (eg: var myvar = function() {…})
  • Objects
    • var bar = new foo();
    • two ways to access properies:
      • dot notation – “my string”.toLowerCase();
      • bracket notation – “my string”[“toLowerCase”](); (this way isi considered harder to read and thus less favored, unless you are using a variable to execute a function on an object)
  • Prototypes
    • when you attach new properties and methods to the prototype they’ll become available to all other objets of that type
  • Pass by reference/value for function calls
    • variables = by value
    • objects = by reference

DOM

Document Object: Common functions to get elements:

  • getElementById() – returns single element from page
  • getElementsByTagName() – returns all elements w/ a specific tag name (watch case though if using xhtml)
  • childNodes – property to retrieve direct descendents of a node

There is NOT a getElementsByClassName() method in spec though. have to write your own function to do this (or use a library).

eg:

function getElementsByClassName(node, classname) {
  var a = [];
	var re = new RegExp('(^| )'+classname+'( |$)');
	var els = node.getElementsByTagName("*");
	for (var i=0,j=els.length; i<j; i++) {
	  if (re.test(els[i].classname))a.push(els[i]); } 
	return a;
}

Navigating the DOM:

Use these methods:

  • childNodes
  • parentNode
  • nextSibling/previousSibling
  • firstChild/lastChild
  • Beware! Some browsers may include text nodes for whitespace between tags (or not) depending on the browser, so the number of DOM elements may not be the number of elements you expect.

getAttribute(name) and setAttribute(name, value) = how to do things like change a link’s HREF attribute.

change an element’s style with myElement.style.property = ‘whatever value‘ where property is the css property you want to change for an element called myElement

Change/add a CSS class: element.className = whatever new class name (may be simpler than changing the style element)

Adding content to DOM:

  • appendChild()
  • insertBefore()
  • replaceChild()

Code formatting best practices:

Should use camel-case for variables, methods, object names

Javascript Libraries

Pros Cons
  • Reliability – higher level of reliability than home-spun code (well-tested)
  • Don’t have to reinvent the wheel, libraries solve common problems, make certain classes of problems easier.
  • Download speed – larger file size than really necessary b/c of extra functionality beyond what you need
  • May be poorly documented – can be frustrating experience b/c many libraries are poorly documented and documentation you need is scattered throughout help-forums across the web (many libraries = unpaid side projects, nice documentation may be last thing on the todo list)

Why use libraries?

  • dom access/traversal/manipulation
    • improves efficiency at retrieval and traversal and so on
    • smooths over inconsistencies between browsers
  • application conviences
    • language extensions – do things the language wasn’t necessarily designed for
      • event handling – create a unified interface for attaching events, maintaining object scope, stopping events, etc.
    • language bridges – fill in missing features an older brower didn’t support
    • ajax – provide a framework for handling successful calls and potential problems such as timeouts
    • templating – makes it quicker to display data on the page by not requiring as much data to be sent because you’ll use a template to format it.
    • improved string handling – ways to filter, capitalize/change case of strings, etc.
    • collections – JS’s array functionality can be limiting, library may give features to make collections more robust (eg: simple iteration, scanning and removing elements, selection of subset, etc)
    • JSON/XML – Libraries can make handling detection of whether a XHR request is JSON or XML automatic, preventing invalid or dangerous information being served up
  • widgets
    • Pre-built components (eg: file browsers, tabbed interfaces, custom dialogs)
    • solve common design issues
    • takes pain out of dealing with complicated edge case

Common libraries:

  • Dojo – focused on widgets and interface elements (to make site more usable/responsive/functional but that will degrade well) to make desktop-like web-applications
  • Prototype – focuses heavily on working with DOM and application conveniences (eg: string handling, enumerations). Approaches problems in a style similar to Ruby
    • Scritp.aculo.us – animation and widget library built on top of Prototype
  • jQuery – library helps with event-handling, to give desktop-like functionality to a web-application, good support for method chaining.
  • YUI (Yahoo User Interface Library) – focus is on pre-built functionalities that are well designed and robust, mix of DOM tools, animation tools, and widgets (eg: calendars)

Ajax

  • Stands for Asynchronous JavaScript and XML, but term is also used more generically as an umbrella term for a number of technologies.
  • way to communicate with the server, returning a chunk of XML, such that you can update the page without having to do a page refresh (allowing audience to continue to interact with the page all teh while)
  • XMLHttpRequest object is oftern referred to as the XHR object
  • Ajax itself = straightforward, handling contingencies may not be.
  • JSON = JavaScript Object notation = uses a subset of JS to safely define and transport data.
    • parsers for JSON available for many servers side languages
    • has been growing in popularity over XML for client/server data transfer
      • smaller in size (less markup required)
      • quicker to parse (native JS)

Planning for Failures

  • Design should account for common failures:
    • How long to wait and what to do if a request times out
    • What to do if the data you get back isn’t what’s expected
    • How to handle multiple requests (esp. if the results come back out of order)
  • Can storyboard/chart or flow-chart what happens on various interactions as a planning technique

Javascript Debugging Techniques

Technique
Implementation
Pros
Cons
Alert
add line of code alert(varname); and will display as a popup
  • Very simple/quick to implement
  • no setup, or extra software needed
  • ineffective for tracing time-sensitive things (where alert throws off your timing)
  • too much hassle for debugging loops (have to click okay too many times)
  • can only show string data, may have to manipulate the data first to make it readable (eg: an array)
Page Logging add an empty div to the page with absolute positioning/scroll overflow, append values to div as needed. Or use a logging library such as log4javascript or fvlogger
  • can display larger/longer data than alert
  • does not interrupt control flow (looping, animation) with pesky popups
  • slightly more work to set up, partially mitigated by copying boilerplate code
  • learning curve to library if used
  • extra div may be in the way if its on the same document
Browser Plugins Install/use software such as DOM inspector built into Firefox, Firebug
  • show what’s actually happening on the page
  • can easily navigate and inspect dom visually
  • may allow console logging
  • Browser-specific, not all browser tools are created equal
  • Requires installation of third party software/plugin
HTTP Debugging Install/use software such as Firebug, Live HTTP Headers, ieHTTPHeaders, Charles
  • Allows tracing of Ajax calls (seeing what is actually being sent or received)
  • Good for certain classes of problems (client/server interaction)
  • Browser-specific, not all browser tools are created equal
  • Requires installation of third party software/plugin