ChocolateChip 2.0 API

ChocolateChip 2.0 is a complete rewrite of many methods to make it work better with ChocolateChip-UI 2.0. Some of these changes were to facilitate an abstraction layer in ChocolateChip-UI so that users swap out ChocolateChip.js, jQuery or Zepto as they need without having to use a different version of ChocolateChip-UI. This version also contains many bug fixes and improvements.

Main Object

$

This is the main object for ChocolateChip.js. Everything else is a child of this. It purpose is to return a DOM node. If no parameter is provided, such as $(), it returns itself. If a string is passed as an argument, it parses the string using the DOM method querySlector. For this reason, $ will always return the first instance of a match. Other matches will be ignored. If you want to get all possible matches, you’ll need to use the $$ method. If you pass in a reference to the window object, document or a DOM node, it will return those. If you pass a function as the argument, it will execute an onDOMContentLoaded event.

Example:

$() // returns the ChocolateChip object
var button = $('.button') // returns the first instance of an element with the class 'button'
$(button) returns the element from the line above
$(window) returns the window object (DOMWindow)
$(document) returns the document element (Document)
$(function() {
   console.log('The DOM is fully ready!')
})

$.extend

This method allows you to extend objects. There are two types of objects you can extend, native and one you define yourself. This method uses Object.keys and Object.defineProperty to add properties to JavaScript’s native objects without poluting their prototypes. This means that if you iterate over the native properties of the extended object, your newly added properties will not show. That’s fine for native objects, however with object you define, if you try to extend one later, those properties would also not be exposed when looping the object’s properties. You can make your added properties show on the objects you’ve create by passing in an extra boolean parameter of true.

If only a property is passed as an argument, extend will add these to the $.

When extending native JavaScript objects you’ll need to include the object’s prototype. See the examples below.

Example:

$.extend(HTMLElement.prototype, {
   click : function() {
      alert('You just clicked me!');
   }
})

// A user defined object:
var obj = {
   firstname: 'Bozo'
};
$.extend(obj, {
   lastname: 'The Clown',
   job: 'Entertainer'
}, **true**) // Pass 'true' to make the new properties enumerable.
for (key in obj) {
    console.log(key)
}

// Only a parameter passed, so extending **$**:
$({
   funny: function() {
      console.log('Ha ha ha!');
   }
})

Array Methods:

each

This method is just a short cut for [].forEach. It works exactly the same. It takes a function as its argument and returns both the index and context of the iteration.

Example:

var listItems = ['one','two','three','four','five'];
listItems.each(function(ctx, idx){
   console.log('Item ' + idx+1 + ' is ' + ctx + '.');
})

eq

This method is used to return an index of an array, particularly with respect to arrays of DOM nodes. This allows you to get a node from a collection based on its order in the collection. So, if we hade a colleciton of nodes called nodes, we could get the first node with nodes.eq(0), the second with nodes.eq(1), the third with nodes.eq(2) and the last with nodes.eq(nodes.length-1).

Example:

$('#menu').findAll('li').eq(4) // Get the fourth menu item

is

This method allows us to pick a node out of a collection based on some attribute or property. It uses ChocolateChip’s HTMLElement.is method. It can accept the following arguemnts: tag, class, attribute. It returns all nodes in the array that match the argument.

Example:

// Find all messages that are p tags:
var msg = $$('.messages').is('p');
// Find all li tags with the class "menu":
var menuItems = $$('li').is('.menu');
// Find all buttons with the attribute "disabled":
var disabled = $$('button').is('[disabled]');

isnt

This method is similar to is but returns all nodes in the collection that do not match the arguemnt passed. Like is it expects a tag, class or attribute as its argument.

Example:

// Find all messages that are not p tags:
var msg = $$('.messages').not('p');
// Find all li tags that do not have the class "menu":
var menuItems = $$('li').is('.menu');
// Find all buttons that are not disabled:
var disabled = $$('button').not('[disabled]');

not

Same as isnt.

has

This method is similar to is but it checks the child nodes of the element and returns all nodes whose child nodes match the argument. Like is it accepts an argument of a tag, class or attribute.

Example:

// Find all messages that contain a span tag:
var msg = $$(".message").has("span");
// Find all items with a child node of class "status":
var complete = $$("p.tasks").has(".status");
// Find all items with a disabled child node:
var disabledItems = $$(".widget").has("[disabled]");

hasnt

This method is the opposite of has in that it returns all nodes whose child nodes do not match the argument passed. Like has it expects an argument of a tag, class or attribute.

Example:

// Find all messages that do not contain a span tag:
var msg = $$(".message").hasNot("span");
// Find all items without a child node of class "completed":
var todo = $$("p.tasks").hasNot(".completed");
// Find all items with a disabled child node:
var disabledItems = $$(".widget").hasNot("[disabled]");

hasNot

Same as hasnt.

prependTo

This method will prepend a collection of nodes to the element it is executed on.

Example:

html: 
<ul id="list1"><li>one</li><li>two></li><li>three</li></ul>
<ul id="list2"><li>four></li></ul>

$('#list1').findAll('li').prependTo('#list2');
// This will result in:
<ul id="list1"></ul>
<ul id="list2"><li>one</li><li>two></li><li>three</li><li>four></li></ul>

appendTo

Like prependTo, this method will append a collection of node to its target.

Example:

html: 
<ul id="list1"><li>one</li></ul>
<ul id="list2"><li>two></li><li>three</li><li>four></li></ul>

$('#list2').findAll('li').prependTo('#list1');
// This will result in:
<ul id="list1"><li>one</li><li>two></li><li>three</li><li>four></li></ul>
<ul id="list2"></ul>

$ Methods

version

The current version of ChocolateChip.js

libraryName

The name of the libary: ChocolateChip. By examining $.libraryName you can tell if $ belongs to ChocolateChip or some other library.

slice

This is an alias for Array.prototype.slice. This is used to reduce an array like collection to an array.

$$

This method is similar to $ except that it returns all nodes that match the supplied selector. You can pass it an optional context from which to begin search for nodes. This can be a string or a node.

Example:

var listItems = $$('li');
var menuItems = $$('li', '#menu');
// Get a node to use as the context:
var sideMenu = $('#sideMenu');
var sideMenuItems = $$('li', sideMenu);

make

This method takes a string of DOM markup and converts it into DOM nodes. The markup defined in the string must be well formed or it will throw an exception. Common erros are inproper tags or mismatched quotation marks.

Example:

var button = $.make('<button id="myButton" class="funButton">Click here</button>');

html

This is an alias for make.

replace

This method will replace one DOM element with another.

Example:

 var newMenu = $.make('<ul id="newMenu"><li>One</li><li>Two</li><li>Three</li></ul>')
$.replace(newMenu, $('#menu1'));

require

This method allows you to dynamically load scripts and execute a callback once the script is full loaded.

Example:

$.require('/scripts/libs/sillyputty.js', function() {
   var sp = new SillyPutty(); // Will not execute until sillyputty.js is full loaded.
});

processJSON

This method will take JSON retrieved by an Ajax request, inject it into the header in a script tag, then remove the script tag. It expects at least one argument, the data to process. You can pass it a second, optional argument to use to identify the data in JavaScript. See the example below. If no second argument is passed, it will be assigned to the variable ‘data’, overwriting any other value that might have been assigned to that variable earlier. As such, it’s always best to supply your own names for you processed JSON data.

Example:

$.ajax({
    url: "data.json",
    success : function() {
        return $.processJSON($.responseText, 'collectionData');
    }
});

noop

This is a “no operation performed” method. It can be used where a function/callback is expected but you don’t want anything to happen.

$(function() {
   $('#order').on('click', function() {
      $.noop; // Nothing will happen.
   })
})

concat

This method utilizes String.prototype.concat to allow you to do efficient string concatenation with a method-like interface.

Example:

$(function() {
    function createButton(options) {
        var id = options.id ? 'id="' + options.id + '" ' : ' ';
        var class = options.class ? 'class="' + options.class + '" ' : ' ';
        var style = options.style ? 'style="' + options.style + '" ' : ' ';
        var submit = options.submit || ' ';
        return $.concat('<button ', id, class, style, '></button>');
    }
})

w

This method takes a space-delimited string of words and returns it as an array where the inidividual words are indeces.

Example:

var str = 'This is an example of a string'
var strArray = $.w(str) // Returns ['This','is','an','example','of','a','string']

isArray

If passed an array as its argument, this method returns a boolean true, otherwise false.

isFunction

If passed a function as its argument, this method returns a boolean true, otherwise false.

isObject

If passed an object as its argument, this method returns a boolean true, otherwise false.

uuidNum

This method returns a random ten digit number.

makeUuid

This method is used by the ChocolateChip cache system to create a uuid for each cache entry. It uses the uuid number stored in the variable below.

uuid

This variable is used by $.makeUuid to create uuids for ChocolateChip’s cache entries.

chch_cache

This object serves as the storage center for both events and data. Therefore you should never overwrite $.chch_cache or you’ll disable the ability of ChocolateChip to register events and cache data in relation to nodes.

Object methods

Object.each

This method allows you to use each to iterate over the properties of a function. It is basically equivalent to writing out a for (key in obj) loop.

Example:

var obj = {
    firstname: 'Joe',
    lastname: 'Bodoni',
    age: 35
};
obj.each(function(key, value){
    console.log("Key is: " + key + ", value is: " + value + ".")
});

/* returns: 
Key is: firstname, value is: Joe.
Key is: lastname, value is: Bodoni.
Key is: age, value is: 35.
*/

Object.key

This method allow you to access the properties of an object using numeric values.

Example:

var obj = {
    firstname: 'Joe',
    lastname: 'Bodoni',
    age: 35
};

obj.key(0); // returns 'Joe'
obj.key(1); // returns 'Bodoni'
obj.key2; // returns 35

Using a key value greater than the number of object properties will return ‘undefined’.

HTMLElement.prototype

The following are all the methods that can operate on a DOM node.

data

Like jQuery and Zepto, the data method allows you to store data in relation to a DOM node. It takes two arguments: the name by which to retrieve the data, and the data itself. This allows you to store multiple pieces of data on a single node.

Example:

$('#mainMenu').data("menuitems", {people: "/data/menus/people/", places: "/data/menus/places", food: "/data/menus/food"});

removeData

This removes the data associated with a node.

Example:

$('#mainMenu').removeData("menuitems");

find

This method finds the first occurrence of the selector from the current node.

Example:

// Find the first instance of '.menu' that is a descendant of '#sidebar'
$('#sidebar').find('.menu');

findAll

This method finds every occurence of the selector from the current node.

Example:

// Find all instances of 'li' that are descendants of '#menu'
$('#menu').findAll('li');

previous

This method returns the previous sibling of the current node. It is equivalent to the ECMAScript 5 method previousElementSibling.

Example:

<p class='paragraph1'>Lorem ipsum</p>
<p class='paragraph2'>Dolor sit amet</p>

$('.paragraph2').previous() // Returns '.paragraph1'

prev

This method is an alias for previous.

next

This method returns the next sibling of the current node. It is equivalent to the ECMAScript 5 method nextElementSibling.

Example:

<p class='paragraph1'>Lorem ipsum</p>
<p class='paragraph2'>Dolor sit amet</p>

$('.paragraph1').next() // Returns '.paragraph2'

first

This method returns the first child of an element.

Example:

$('#menu').first() // returns the first child of '#menu'

last

This method returns the last child of an element.

Example:

$('#menu').last() // returns the last child of '#menu'

childElements

This method returns all the child nodes of an element, minus empty text nodes. It is equivalent to the ECMAScript 5 method children.

Example:

$('#menu').childElements() // Returns all child elements of '#menu'

siblings

This method get all the sibling elements of a node.

Example:

$('#paragraph5').siblings() // Returns all child elements of '#paragraph5'

parent

This method returns the parent of a node. It is the same as accessing the ECMAScript 5 property parentNode.

Example:

$('#menu').parent() // Returns the parent node of '#menu'

ancestor

This method allows you to get a specific ancestor of a node. You can use a tag, class, attribute or number as the filter for singling out the node. A number will indicate how far back the ancestor is. This method returns the first match for the provided selector.

Example:

// Will return the third ancestor tag back from the current node:
var theAncestor = $("#someID").ancestor(3);
// Will return the element with id of "#main" 
// if it is an ancestor of "#someID":
var theAncestor = $("#someID").ancestor("#main");
// Will return an element with a class of ".myView" if
// it is an ancestor of "#someID":
var theAncestor = $("#someID").ancestor(".myView");
// Will return a subview tag if it is an ancestor of "#someID":
var theAncestor = $("#someID").ancestor("subview");

closest

This is an alias for ancestor for compatibility with jQuery/Zepto.

is

This method returns the node if it matches the tag, class or attribute provided as an argument.

Example:

var p = $("#content").is('p');
// Return the element if it has the class 'content':
var content = $('article').is('.content');
// Return the element if it has the atribute 'disabled':
var disabled = $('button').is('[disabled]');

isnt

This method returns the node if it does not match the tag, class or attribute provided as an argument.

Example:

var notParagraph = $("#content").not('p');
// Return the element if it does not have the class 'content':
var notContent = $('article').not('.content');
// Return the element if it has the atribute 'disabled':
var enabled = $('button').not('[disabled]');

not

This is the same as isnt.

has

This method returns the node if one of its child nodes matches the tag, class or attribute provided as an argument.

Example:

// Return the element if it has a child node of this tag type:
var p = $('#content').has('p');
// Return the element if it has a child node with this class:
var hasNewContent = $('#content').has('.new');
// Return the element if it has a child node with this attribute:
var somethingDisabled = $('#content').has('[disabled=disabled]');

hasnt

This method returns the node if one of its child nodes does not match the tag, class or attribute provided as an argument.

Example:

// Return the element if it does not have a child node of this tag type:
var p = $('#content').hasNot('p');
// Return the element if it has a child node with this class:
var doesntHaveNewContent = $('#content').hasNot('.new');
// Return the element if it does not have a child node with this attribute:
var notDisabled = $('#content').hasNot('[disabled=disabled]');

hasNot

This is the same as hassnt.

clone

This method clones the node it is execute on. If a boolean value that evaluates to true is passed as an argument, the method will clone the node and all its child nodes, otherwise it clones only the node itself.

Example:

var menuEmpty = $("#menu").clone(); // Clone only the node.
var menuComplete = $("#menu").clone(true); // Clone the node and its child nodes.

wrap

This method allows you to enclose a node in markup. The markup is passed as a string argument.

Example:

$("#menu").wrap("<nav id='main'></nav>");

unwrap

This method will remove the parent node container the node, escentially making it the child of it grandparent node. See the example below:

Example:

<header>
   <nav>
      <div id="#menu"></div>
   </nav>
</header>

// Executing:
$('#menu').unwrap()

// Will result in:

<header>
   <div id="#menu"></div>
</header>

text

This method can return the text nodes contained by the target element, or add text to a node. If no argument is provided, it returns the node’s text. If a string of text is provided, it inserts the string as a text node of the target node. When this method returns text, it will not contain styling or semantic markup. It only returns only plain text with spaces. Be aware that when you use this method to add text to a node, the text will replace any other child nodes within the target node.

Example:

$('#menu').find('li').first().text("Menu Item One");
// Pass in a variable of a string:
var menuContent = "Menu Item One";
('#menu').find('li').first().text(menuContent);
// Get the text of the last menu item:
('#menu').find('li').last().text();

fill

This method will replace the contents of the target node with the argument, which can be a text string or the reference to a DOM node. This has been deprecated. For text use the text method above and for node injection use insert or html present below.

empty

This method will remove all child nodes from the target element.

Example:

$('#menu').empty();

remove

This method will remove a node from the document. While doing so it will attempt to remove any events attached by check the event cache for that element, as well as clear any data associate with it in the data cache.

Example:

$('#menu').remove();

insert

This method allows you to insert markup into another node. The first argument is the content to insert. This can be a string of valid markup, or a reference to an existing HTML fragement or node. The second argument is optional. If no second argument is provided, the content will be inserted after any other child nodes contained in the target node. Posible positional arguments are “before”, “after”, or a number indicating the position in relation to the node’s other child nodes. If you pass a number greater than the actual number of child nodes, the content will be inserted after the last valid child node. A number value of 1 would be the first child position, 2 – second child position, 3 – third child position, etc.

Example:

var newPara = "<p>Lorem ipsum dolor sit amet.</p>"
$('#main').insert(newPara) // Insert after other child nodes.
$('#main').insert(newPara, "before") // Insert before other child nodes.
$('#main').insert(newPara, "after") // Insert after other child nodes.
$('#main').insert(newPara, 2) // Insert as the second child node.
$('#main').insert(newPara, 5) // Insert as the fifth child node.

html

This method complete replaces the node’s content with the content passed as an argument. This can be a string of valid markup or a refrence to an HTML fragment or node. This is the same as the jQuery/Zepto method.

Example:

$('#menu').html("<li>one</li><li>two></li><li>three</li>");
var menuItems = "<li>one</li><li>two></li><li>three</li>";
$('#menu').html(menuItems);
var newItems = $('#sidebar').findAll('li');
$('#menu').html(newItems);

prepend

This method will insert the provided content before all other child nodes of the target node. This is the same as using element.insert(content, “before”) or element.insert(content, 1). This is mainly for compatibility with jQuery/Zepto.

Example:

var menuItems = "<li>one</li><li>two></li><li>three</li>";
$('#menu').append(menuItems);
var newNode = $.make('<p>A new node!</p>');
$('#content').prepend(newNode);
$('#content').prepend('<p>A new node!</p>');

append

This method will insert the provided content after all other child nodes in the target node. This is mainly for compatibility with jQuery/Zepto.

Example:

var menuItems = "<li>one</li><li>two></li><li>three</li>";
$('#menu').prepend(menuItems);
var newNode = $.make('<p>A new node!</p>');
$('#content').append(newNode);
$('#content').append('<p>A new node!</p>');

before

This method will insert the content before the target node, making the inserted content the previous sibling of that node.

In this example, we use before to insert a numbered title before each paragraph in the document.

Example:

$.itemNumber = 1;
$$("p").forEach(function(item) { 
   item.before("<h1>Title " + $.itemNumber + "</h1>");
   ++$.itemNumber;
});
$.itemNumber = null;

after

This method will insert the content after the target node, making the inserted content the next sibling of that node.

In this example, we use after to insert an addendum after each paragraph.

Example:

$.itemNumber = 1;
$$("p").forEach(function(item) { 
   item.after("<p>Addendum " + $.itemNumber + "</p>");
   ++$.itemNumber;
});
$.itemNumber = null;

attr

This method can return the value of an attribute or set it to the provided value. If only an attribute is provided, it will attempt to return the value of that attribute on the node. If the attribute does not exist, it will return ‘undefined’. If an attribute and a value are passed as arguments, the method will attempt to set that attribute with that value on the node.

Example:

$('#menuLink').attr('href'); // return the href of a link
$('#menuLink').attr('href', '/specials.html'); // set the href of the link

prop

This is the same as attr and is included for compatibility with jQuery/Zepto.

removeAttr

This method removes the provided attribute from the node.

Example:

$('#menu').removeAttr('disabled');

hasClass

This method returns a boolean value. If the node has the class, true, otherwise false. This allows you to test if the node has the class or not.

Example:

// Get all articles and display them if they have content:
$$('article').each(function(article) {
    if (article.hasClass('content')) {
        article.css('display', 'block');
    }
});

addClass

This method adds the provided class to the node.

Example:

$('nav').addClass('menu');

removeClass

This method removes the provided class from the node.

$('nav').removeClass('menu');

toggleClass

This method allows you to toggle a class on and off an element, or toggle between two classes. If only one class is passed as an argument, it is added then removed, then add, etc. If two class names are provided, the first is added, then the second, then the first, etc.

Example:

// Toggle the 'hover' class:
$("#item").toggleClass("hover");
// Toggle between these two classes:
$("#item").toggleClass("selected", "unselected");

toggleClassName

This method is the same as toggleClass and exists only to fullfil the same ability to toggle to classes for jQuery and Zepto when ChocolateChip.js is used in ChocolateChip-UI. That’s because toggleClass in jQuery and Zepto only toggle a single class by adding and removing it from a node. This allows toggle two classes on and off.

val**

This method returns the value of a form element, or, if a value is passed as an argument, the form element’s value is set to that.

Example:

// Get the value of a text input:
var msg = $('input[type=text]').val();
// Set the value of an input:
$('textarea').val('This is some default text');

disable

This method disables and element by adding a ‘disabled’ attribute and changing the cursor to behavior.

Example:

$('button').disable();

enable

This method enables an element that was previously disabled.

Example:

$('input[type=range]').enable();

getTop

This method returns the position (y value) of an element from the top of the document. The element does not need to be absolute positioned. This returns an integer representing pixels.

Example:

var buttonTop = $('uibutton[ui-implements=done]').getTop();

getLeft

This method returns the position (x value) of an element from the left of the document. The element does not need to be aboslutely positioned. This returns an integer representing pixels.

Example:

var buttonLeft = $('uibutton[ui-implements=done]').getLeft();

css

This method can get the style or set the style of a node. If only a style property is passed, it returns that property’s current value on the node. If you are only applying one property definition, you can pass the arguments as two quoted strings separated by commas. Otherwise, for more complex styling you can pass an object of key/value pairs to define the style you wish to apply.

Example:

/* Getting CSS values */
// Get the width:
var width = $('#main').css('width');
// Get the background color:
var backgroundColor = $('#main').css('background-color'); 
// Get the top padding:
var padding = $('#main').css('padding-top');
// Get the font size:
console.log($("#item").css("font-size"));

/* Setting single key value pairs */
// Set the font:
$('#main').css('font', 'bold 24px/32px Myriad');
$('#main').css('padding', '20px');
$('#main').css('height', '200px');

/* Setting complex CSS values */
$('#main').css({'width': '200px', 'height': '500px', 'background-color': 'red'});
var styles = {
   position: 'absolute',
   top: '200px',
   left: '350px',
   border: '1px solid red',
   padding: '20px',
   'background-color': 'yellow'
}
$('#main').css(styles);

Note:

Be aware that when getting a CSS property’s value, this method always returns a string. This means that if you try to do math operations with the value, you’ll wind up with string concatenation or a result of NaN. If you want the dimensions or other integer values, you’ll need to use parseInt() to convert those values to integers. Then you can perform math operations on the value:

var width = $('#rightCol').css('width') // Returns 300px
width = parseInt(width, 10); // Returns integer 300
// Increase #rightCol's width by 20 pixels:
width += 20;
// Don't forget to tag on the 'px' length at the end!
$('#rightCol').css('width', width + 'px')

bind

This method binds events to nodes along with a callback. A third optional argument can set the capture phase. By default it is false, but you can pass a boolean true value to change that behavior. In most cases you want the capture phase to resolve to false.

ChocolateChip.js uses its caching system to keep track of which events you’ve bound to an element to facility unbinding them at a later time. Please see the documentation for unbind for more information.

Example:

var doSomething = function() {
   console.log("I'm doing it now.");
};
$("#doIt").bind("click", doSomething);
// or:
$(".stop").bind("touchend", function() {
   console.log("Time to put an end to this!");
   this.remove();
});

unbind

This method unbinds an event from a node. There are several ways in which you can unbind events from a node. The simplest is to just execute unbind directly on the node. This will unbind all events attached to the node. This is good to do if you intend on removing or replacing the node with other content.

Example:

// Remove all events bound to the body tag:
$('body').unbind();

You can be more specific about which events to unbind by passing in an event type. Please not that it is possible to have multiple events of the same type attached to a node. ChocolateChip’s system for caching event information keeps track of callbacks even when you use an anonymous function. However, because an anonymous function has no name, the only way that it can be removed is by removing the event it is associated with. For example, if you have several click events attached to the same button and they all use anonymous functions as callbacks, to remove one callback associated with the click event you’ll actually have to remove all anonymous functions associated with the click event bound to that button.

 $('#myButton).bind('click', function() {
    console.log('You just clicked a button.');
 });
 $('#myButton).bind('click', function() {
    alert('Stop clicking me!!!');
 });
 $('#myButton).bind('touchstart', function() {
    console.log('You just touched me.');
 });
 // The above button now has to click events that do two different things.
 // Remove all click events, leaving the touchstart event:
$('#myButton').unbind('click');

If you passed a named function as a callback for an event, you can be more specific and only unbind the event with that function:

var saySomething = function() {
   alert('This is what I have to say!');
};
$('button').bind('click', saySomething);
$('button').bind('click', function() {
   console.log('This is another annoying message.');
});
// Unbind only the event with the function 'saySomething':
$('button').unbind('click', saySomething);

You can also use the capture phase as a third argument to be more granular, if you have events and function with different capture phases.

delegate

This method allows you to attach a listener to a parent element to listen for events on a descendant node. This becomes very useful when you’re dealing with something like a long list of links. Instead of having to attach an event to every link, you can attach the listener to the parent container. Using delegation allows you to attach an event on the parent and not worry about how many descendant elements there are, or even if they are present yet. They might be injected into the document after the listener is attached, allowing you to capture events on them dynamically as they are generated.

To delegate and event you first indicate what parent node you want to listen on, followed by the node type that will be the target of the event, followed by a callback and finally an optional capture phase. By default the capture phase is resolved as false. Like bind, in most cases you want it to be false.

When you pass a callback, you can capture a reference to the context of the element that is the target of the event by pass a variable in the callback’s parenthesis. You can then reference that variable inside the body of the callback. In the example below, the variable ‘paragraph’ with refer to the p tag that gets clicked.

Example

$("body").delegate("p", "click", function(paragraph) {
  paragraph.css("background-color", "yellow");
});

You can also check for attributes on the event target to filter what you do with a node.

// Check for an attribute on the event target:
$("app").delegate("button", "touch", function(item) {
   // Check for button with "ui-implements" attribute:
   if (item.getAttribute("ui-implements") === "back") {
       item.addClass('selected');
   }
});

undelegate

Like unbind, this method allows you to remove a delegate event from a node. The arguments work the same as unbind. So undelegate() with no arguments will remove all event bindings. Passing in only an event will undelegate all of those events, passing in an event with a reference to the callback with remove only the event associated with that callback.

Example:

$("body").undelegate("click");

var markSelect = function(item) {
    item.addClass('selected');
};
$("app").delegate("touch", markSelect);

trigger

This method sends the provided event to the target element. For example, if you sent a click event to a button, it would react just as if you had actually clicked on it.

Example:

$("#clickLink").bind("click", function() {
   // Trigger a click event on a hidden button:
   $("#hiddenButton").trigger("click");
});

on

This method is the modern equivalent of bind and delegate both. You use it just as you would bind and delegate.

Example:

/* Examples of binding events with 'on' */
var doSomething = function() {
   console.log("I'm doing it now.");
};
$("#doIt").on("click", doSomething);
// or:
$(".stop").on("touchend", function() {
   console.log("Time to put an end to this!");
   this.remove();
});

/* Examples of event delegation with 'on' */
$("body").on("p", "click", function(paragraph) {
   paragraph.css("background-color", "yellow");
});

off

This method is equivalent to both unbind and undelegate. You use it the same way you would those two methods.

Example:

$('#myButton').off('click');
// Unbind a click event with the callback "saySomething":
$('button').off('click', saySomething);
// Unbind a delegate click event:
$("body").off("click");
// Unbind a delegate click event with the callback "saySomething":
$("app").off("touch", markSelect);

anim

A method to create dynamic CSS3 transitions. The method takes three arguments, an object literal of CSS values to animate, followed by a value for the duration in milliseconds, and an easing descriptor. If no easing is provided, it defaults to linear, if no duration is provided it defaults to half a second.

element.anim(options, duration, easing);

Example:

$("#animate").on("click", function() {
   this.anim({"-webkit-transform": "rotate3d(30, 150, 200, 180deg) scale(3) translate3d(-50%, -30%, 140%)", 
   "opacity": .25, 
   "-webkit-transform-style" : "preserve-3d", 
   "-webkit-perspective": 500}, 
   2, 
   "ease-in-out");
});

You can include in the object an optional callback to execute when the animation ends:

 function saySomething() {
     alert('The animation just ended.');
 }
$("#animate").on("click", function() {
   this.anim({"-webkit-transform": "rotate3d(30, 150, 200, 180deg) scale(3) translate3d(-50%, -30%, 140%)", 
   "opacity": .25, 
   "-webkit-transform-style" : "preserve-3d", 
   "-webkit-perspective": 500, 
   onEnd: saySomething }, 
   2, 
   "ease-in-out");
});

UICheckForOverflow

This method test to see if an element whose overflow property is set to ‘hidden’ is hiding any content overflow.

String Methods

capitalize

This method will capitalize the first letter of a string, as for the first word of a sentence.

Example:

var name = "robert";
name.capitalize(); // returns Robert

capitalizeAll

This method will capitalize the first letter of each word in a string.

Example:

// returns Get Out Now
var name = $.capitalize("get out now");

camelize

This is a method to turns a hyphenated word into camel case. This method operates directly on a string. See example below.

Example:

var str = 'background-color';
console.log(str.camelize) // outputs: backgroundColor

deCamelize

This is a method to turn a camel case word into a hyphenated word. This method operates directly on a string. See example below.

Example:

var str = 'backgroundColor';
console.log(str.deCamelize) // outputs: background-color

$ Methods

xhr

This method allows you to execute an Ajax operation. You pass in an object literal of the properties you wish to execute. It expects at a minimal a URL to access.

Syntax:

$.ajax({
    url : (a valid url),
    type : (get, post, put, delete),
    async : (true or false),
    params : (any data you wish to include),
    success : success,
    error : error,
});

Example:

/* This will replace the content of the paragraph above with the content of the requested document. If the script is successful, it will execute the success callback, and if it is not, it will execute the error callback.
*/
 var content = $("#content");
$.xhr({
     url : "data.html",
    success : function(data) {
        content.html(data);
     },
     error: function(data) {
         content.html("<h4>There was an error while trying to get the file.</h4>");
         if (data.status === -1100) {
             content.append('<h2>The file does not exist.</h2>');
         }
     }
});

ajax

This is just an alias for $.xhr described above.

xhrjson

This is a method that allows you to do simple JSON data-binding to markup.

<div id="content_02"><span id='firstName'>Joe</span> <span id='lastName'>Bodoni</span> is a <span id='job'>great waiter at a restaurant downtown.</span><span id='role'></div>

/* Here we do a request for a JSON file. If the request is successful, the returned data gets mapped to the object of document elements. This results in the data being inserted into the designated elements of the document. If there is an error, an error message will be displayed. */
var content2 = $("#content_02");
$.xhrjson("person.json", { 
    "firstName": "#firstName",
    "lastName": "#lastName",
    "role":"#role",
    "job": "#job",
    errorCallback : function() {
        content2.insert("<h4>There was a problem processing your request. Try again later.</h4>");
    }
});

delay

This method allows you to execute a function with a delay, like setTimeout:

Example:

$.delay(function() {
   console.log("This message is delayed by two seconds.");
}, 2000);

defer

A method to postpone the execution of a function until the callstack is clear.

Example:

$.defer(function() { 
   console.log("This comes before Squawk!"); 
});

enclose

A method that allows you to execute one function within the execution of another function.

Example:

var hello = function(name) { return "Hello, " + name + "!"; };
hello = $.enclose(hello, function(func) {
   return "Before I said, \"" + func("Stan") + "\" I thought about it for a while.";
});

compose

Method to return the composition of several functions, where each function consumes the return value of the function that follows.

Example:

var greet = function(name) { return "Hi there, " + name; };
var exclaim  = function(statement) { return statement + "!"; };
var remark = function(remark) { return remark + " You know I'm glad to see you."; };
var welcome = $.compose(remark, greet, exclaim);
console.log(welcome('Jeff')); // => Hi there, Jeff! You know I'm glad to see you.

events

An array of events to be removed before a node is deleted from a document. This array is attached directly to the $ object.

loadEvent

A method to chain load multiple functions to execute when the document finishes loading. This is equivalent to the load event on the body tag.

Example:

var myFunction = function () {
   return true;
};
$.loadEvent(myFunction());

ready

Method to determine when the DOM is ready for manipulation and thereupon fire a block of code contained in an anonymous function passed to it as an argument. If there are mulitple instances of this method, it’s arguments will be chained and called sequentially with one registration of the DOMContentLoaded event.

Example:

$.ready(function() { 
   console.log("The document is ready for action!"); 
});

There are several other variants of this method that you can use:

// Like jQuery and Zepto:
$(document).ready(function() { 
   console.log("The document is ready for action!"); 
});

// Just pass in an anonymous function around the code you wish 
// to execute to the $() method:
$(function() { 
   console.log("The document is ready for action!"); 
});

importScript

A method to import external scripts into the document. This method does so by inserting a script tag into the head of the document, causing the script to load. As such, this method does not suffer from cross-domain scripting issues.

Example:

$.importScript("https://bozo.com/scripts/myScript.js");

Variables

iphone

Returns true if on an iPhone.

ipad

Returns true if on an iPad.

ipod

Returns true if on an iPod.

ios

Returns true if on a device runing iOS.

android

Returns true if on a device running Android.

webos

Returns true if on a device running WebOS.

blackberry

Returns true if on a Blackberry device.

touchEnabled

Returns true if the device supports touch interaction.

online

Returns true if the device has WiFi or a network connection.

standalone

Returns true if the app is running as a pinned site, as apposed to running in a browser

ios4

Returns true if on iOS 4.

ios5

Returns true if on iOS 5.

userAction

Returns ‘click’ on desktops or devices without touch interfaces, and returns ‘touchend’ on touch devices.

mobile

Returns true if the device is mobile.

desktop

Returns true if the device is a desktop.

localItem

Set a key/value pair to the browser’s localStorage, or retrieve a key value. If you pass only a key, it returns the key’s value if that key is present in localStorage. Otherwise, passing a key and a value will set these on localStorage.

Example:

$.localItem("clientFirstName", "Robert");
var clientFirstName = $.localItem("clientFirstName");
console.log("The client's name is: " + clientFirstName");

deleteLocalItem

// Remove 'clientFirstName' from localStorage:
$.deleteLocalItem('clientFirstName');

This method deletes the provided key and its value form localStorage.

clearLocalItems

This method clears all items from localStorage.

$.clearLocalItems();

Templating

ChocolateChip provides its on built-in templating. However, although it is convenient and powerful for most templating needs, if you are dealing with large datasets where speed is important, you should consider a dedicated templating solution.

templates

This is an object onto which you can store your templates. You can choose between three different templating styles: JSP, Mustache or Django.

JSP style tags:

The delimiters for this are “”. You can include any JavaScript code you want to execute in the template inside these delimiters. To output the value of a variable, use “”.

Example:

var templates.ingredients =
     "<% /* Check if this recipe has ingredients: */ %>\
     <% if (!!recipe.ingredients) { %>\
          <ol class='ingredients'>\
                <% recipe.ingredients.forEach(function(ingredient) { %>\
                     <li><%= ingredient %></li>\
                <% }); %>\
          </ol>\
     <% } %>";

Mustache style tags:

The delimiters for this are “{{” and “}}”. You can include any JavaScript code you want to execute in the template inside these delimiters. To output the value of a variable, use “${” and “}”.

Example:

var templates.ingredients =
     "{{ /* Check if this recipe has ingredients: */ }}\
     {{ if (!!recipe.ingredients) { }}\
          <ol class='ingredients'>\
                {{ recipe.ingredients.forEach(function(ingredient) { }}\
                     <li>${ ingredient }</li>\
                {{ }); }}\
          </ol>\
     {{ } }}";

Django square bracket style tags:

The delimiters for this are “[[” and “]]”. You can include any JavaScript code you want to execute in the template inside these delimiters. To output the value of a variable, use “$[” and “]”.

Example:
var templates.ingredients =
“[[ /* Check if this recipe has ingredients: */ ]]\
[[ if (!!recipe.ingredients) { ]]\

    \
    [[ recipe.ingredients.forEach(function(ingredient) { ]]\

  1. $[ ingredient ]
  2. \
    [[ }); ]]\

\
[[ } ]]”;

Nesting Templates:

You can break down complex templates into manageable modules which you can nest. This allows you to update the nested templates separately from the parent, or the other way around. It’s probably a good idea to name nested templates so that their name reflects their relation to the parent template they belong to. Here’s how to do it. Just define the sub-templates the same way you would define a normal template, as a value on $.templates. Then, when building out the string for the parent template you concatenate the sub-template’s variable. This would be something like this:

$.templates.parent_child = 
 "<ol>\
 [[ ancestry.parent.child.forEach(function(child) { ]]\
     <li>$[ ancestry.parent.child.name ]</li>\
 [[ }); ]]\
 </ol>";

 $.templates.parent = 
 "<div>
     <p>$[ ancestry.parent.firstName ] $[ ancestry.parent.lastName ] </p>"
     + $templates.parent_child + 
 "</div>";

As you can see above, the parent_child template gets concatenated in the parent template. In the more complex example below, notice that I’m doing a conditional check to make sure the values that the nested templates depend on exist before outputting them in the parent template. Or you could put that conditional check in the nested template itself. Your call to make.

 /* The next two templates will be nested in $.templates.recipes: */
 $.templates.recipes_ingredients = 
     "<cellsubtitle>\
          <div>Ingredients</div>\
          <ul>\
                [[ recipe.ingredients.forEach(function(ingredient) { ]]\
                     <li>$[ ingredient ]</li>\
                [[ }); ]]\
          </ul>\
     </cellsubtitle>";
 $.templates.recipes_directions = 
     "<celldetail>\
          <div>Directions</div>\
          <ol>\
                [[ recipe.directions.forEach(function(direction) { ]]\
                     <li>$[ direction ]</li>\
                [[ }); ]]\
          </ol>\
     </celldetail>";
 /* The above two templates are nested in this template: */
 /* Before inserting the nested templates, we do a conditional check to make sure the current iteration of the JSON object has an ingredients and directions array: */
 $.templates.recipes = 
     "[[ recipes.forEach(function(recipe) { ]]\
          <tablecell class='ui-no-hover'>\
                <celltitle>$[ recipe.title ]</celltitle>\
                [[ /* A conditional check for recipe ingredients: */ ]]\
                [[ if (!!recipe.ingredients) { ]]"
                      + $.templates.recipes_ingredients +
                "[[ } ]]\
                [[ /* A conditional check for recipe directions: */ ]]\
                [[ if (!!recipe.directions) { ]]"
                     + $.templates.recipes_directions +
                "[[ } ]]\
          </tablecell>\
     [[ }); ]]";

template

A method to parse a JavaScript template and populate it with JSON data. You define the template as a string (see $.templates above) consisting of markup along with JavaScript enclosed in special delimiters. The $.template method parses the JSON object and passes it to the template, after which you can insert it where you wish.

Example:

var result = $.template("ingredients", data);
$(function() {
   $("#recipe").insert(result);
});

One thing I want to point out in the above example, when you define a template with $.templates, such as $.templates.ingredients = “…” when you go to use the template in the $.template method, you don’t need to use $.templates.ingredients, you can just give the name of the template, “ingredients” in this case. The $.template method already knows to retrieve the template from the $.templates object.

UIUpdateOrientationChange

A method for outputting a class on the body tag to identify the orientation of the mobile device when the device’s orientation changes. In landscape mode it puts the class “landscape” on the body tag and in portrait mode it puts the “portrait” on the body tag. There can only be one or the other on the body tag at any given time. This class is to enable the use of styles based on the orientation of the device. You can create styles using these class as in the example below.

Example:

body.portrait app > view {
   background-color: green;
}
body.landscape app > view {
   background-color: orange;
}

UIListenForWindowResize

A method to imitate orientation change on mobile devices. It puts a class on the body tag to mimic the orientation of the mobile device when the window is resized. If the window is wider than it is tall, it outputs the class “landscape” on the body tag, and when it is taller than it is wide, it outputs “portrait” on to the body tag. This allows you to testing for orientation change on the desktop for landscape and portrait modes.

Example:

body.portrait app > view {
   background-color: green;
}
body.landscape app > view {
   background-color: orange;
}

kvo

A method for set up key value observers for basic data binding. This allows you to register observers on UI elements to watch for a change in a value. This value could be that of some input or control or of an object. When the observed values change, the observers capture that change and update themselves automatically. In respect to MVC (model, view, controller) practice his allows you to decouple your models from your UI (views). This is especially useful for complex and interactive user interfaces.

In the case of the following HTML we can put together an example in which we want the label to be aware of the value of the text input field:

Example:

 <input id="textinput" type="text">
 <br>
 <label id="labeltext">Doh!</label>
 <script>

 $(function() {
     var input = $("#textinput");
     var label = $("#labeltext");
     kvo.registerObserver(label, "text");
     //var currentValue = "Bozo;
     label.keyWillUpdate = function(object, key, currentValue, newValue) {
          if (newValue) {
                this.innerText = input.value;
          } else {
                this.innerText = currentValue;
          }
     };
     input.onkeyup = function() {
          kvo.set("text", this.value);
     };
 });
 </script>

form2JSON

A method that converts form values to a JSON object. This can be converted to a string for sending to the server with a GET or POST request, or stored on the client side in localStorage or the client side SQLite database.

Paramters:

  • selector: a valid selector for the form to be processed.
  • delimiter: a character to use as a delimiter for the marking of JSON member relations in the form element’s name values (see example below). This defaults to “.”, but you can use any other character that suits your purposes.

For this method to work properly you must name all form elements that you want to retrieve so that they match the structure of the resulting JSON object you would like. You use “.” to indicate the sub objects of the JSON object. For example, if your form was for signing up a user, you might have inputs with names such as:

 <form id="newUser"> 
     <input type="text" name="newUser.name.first"></input>
     <input type="text" name="newUser.name.last"></input>
     <input type="text" name="newUser.address.street"></input>
     <input type="text" name="newUser.address.city"></input>
     <input type="text" name="newUser.address.state"></input>
     <input type="text" name="newUser.address.zip"></input>
     <input type="text" name="newUser.phone"></input>
     <input type="text" name="newUser.email"></input>
 </form>
 <script>
     $("#main > navbar > uibutton[ui-implements=done]").bind("click", function() {
          var formData = $.form2JSON('#personalInfo');
          formData = JSON.stringify(formData);
          window.location = "ajax/template.html?" + formData;
     });
 </script>

This would result in a JSON object like this:

 {"newUser":
     {"name": 
          {"first": "someValueHere"},
          {"last": "someValueHere"}
     },
     {"address":
          {"street": "someValueHere"},
          {"city": "someValueHere"},
          {"state": "someValueHere"},
          {"zip": "someValueHere"}
     },
     {"phone": "someValueHere" },
     {"email": "someValueHere"}
 }

Disabled form elements or ones which have no value will be ignored.

If you need to create an array from something like a set of choices, you’ll need to marke the name with brackets “[]” to indicate that it’s an array:

 <div>Favorite food</div>
 <p>
     <label>Salad:</label>
     <input type="checkbox" name="user.favoriteFood[]" value="salad">
 </p>
 <p>
     <label>Pizza:</label>
     <input type="checkbox" name="user.favoriteFood[]" value="pizza">
 </p>
 <p>
     <label>Chicken:</label>
     <input type="checkbox" name="user.favoriteFood[]" value="chicken">
 </p>
%d bloggers like this: