PCS JS Immersion


Prelude: Overloading, Accessors, and Chaining


"Overloading" a function means varying its purpose depending on the number and type of its arguments.

Exercise: write an overloaded function.


An "accessor" function is overloaded to both get and set an object property.

Exercise: write an accessor method for a constructor of your choice.


Setters may return the same object they manipulate, which affords "chaining".

Exercise: write a set of chainable methods to support the following command: js obj.name('Barney').species('dinosaur').color('purple').name();

The "Magic Bag" wrapper object

function magicBag(selector) {
  var matchingThings;

  if (selector[0]==='#') {
    matchingThings = [document.getElementById(selector)]
  } else if (selector[0]==='.') {
    matchingThings = document.getElementsByClass(selector);
  } else {
    matchingThings = document.getElementsByTagName(selector);

  return {
    things: matchingThings,
    // setter methods:
    magic: function () {
      return this;
    shazam: function() {
      return this;
    kaboom: function() {
      return this;

// possible use:
var tds = magicBag('td');

// more informative name:
var $tds = magicBag('td');

JQuery objects are a kind of Magic Bag!

Some Overloaded Meaning of $

For lots more detail, see jquery's documentation.

Element Retrieval:

$(selector)  // "#id", ".class", or "tag"
$([node0,node1, ...])

//  all these return $stuff, as in:
var $stuff = $('tr'); //--> builds magic bag of all <tr> elements

Element Creation:

// example:
var $div = $('<div>');

// example:
var $img = $('<img>',{id:'id', href:'url'})

On-ready Event Handlers:



$stuff.children() // elements only
$stuff.contents() // elements and text

Set Reduction/Filtering:

// Singletons:

$stuff[n]    //--> nth item as DOM element
$stuff.eq(n) //--> nth item as jq singleton

var $stuff = $('td');
var stuff0 = $stuff[0];
var $stuff0 = $stuff.eq(0);
stuff0 instanceof HTMLElement // true
$stuff0 instanceof $ //true

// Plurals:
$stuff.has(selector | element)
$stuff.is(selector | Fn) --> boolean
$stuff.not(selector | Fn | stuff)

Set Addition:


Element Attachment/Detachment:


Content Replacement:


Setting Classes:



$stuff.animate({cssProp:targetVal}, duration)

JQuery exercise

In a new file, write a constructor that creates a grid of TreeHouse badges using jQuery.

When a badge is clicked, do some kind of animation with it. Be creative!

JQuery Iteration

Exercise: each vs. forEach

  • array.forEach(fn) --> calls fn(item,n)

  • $stuff.each(fn) --> calls fn(n,item) with item as 'this'

Implicit Iteration

$allcells.html(function(num) {
    return num;