Getting and Adding Text

Leave a comment

For people who like to mess with what’s on a page

Sometimes you need to get the text of an element, or add some text to an element. ChocolateChip provides a versatile set of tools for doing this. Here are the methods:

  1. Element.text()
  2. Element.fill()
  3. Element.empty()
  4. Element.innerText
  5. Element.outerText
  6. Element.textContent
  7. String.trim()
  8. String.capitalize()
  9. String.capitalizeAll()
  10. $.concat()


The $.text() method can serve you in two ways: it can get the text of the element if no value is passed as an argument. If a string of text is passed as an argument, $.text() will fill the element with that text. When $.text() gets text, it preserves the white space between nodes. If you really want to collapse the text and eliminate any white space, use the textContent property described below. Here are some examples of $.text() in action:

	<p>The first paragraph is always the best.</p>
	<p>Sometmes the second is good enough.</p>
	<p>But does anyone ever pay attention to the third paragraph?</p>
		<li>Care Bears</li>
$(function() {
    // Will return "The first paragraph is always the best"
    // Will change the contents of the third paragraph.
    $("p:nth-of-type(3).text("The third paragraph is different now.");
    // Get the text of the fourth list item.
    var listItem = $("li:nth-of-type(4)").text();
    // Change the fourth list item to "Anacondas"
    console.log("The fourth list item was: " + listItem + ", but now it is: " + $("li:nth-of-type(4)").text());


This method empties and element of all its child nodes.

$(function() {


This method returns the text of the element with white space formatting. A single spece separates inline elements and a new line separates block elements.

		<td>Row One Item One</td>
		<td>Row One Item Two</td>
		<td>Row Two Item One</td>
		<td>Row Two Item Two</td>

$(function() {

The above code would output the following to the console:

Row One Item One	Row One Item Two
Row Two Item One	Row Two Item Two

When using innerText to set the content of an element, be aware that it does not parse the string for HTML elements. Any HTML markup in the string is output as text. This is great if you want to prevent malicious script injection in your app.


Like innerText, outerText returns the text of the target element’s parent node, which would include the text of any other child nodes that the parent has. Similarly, if you assign a text value to the element’s parent using outerText, all of the parent’s child nodes will be replaced with the new text. This is the same as the behavior of outerHTML.


In contrast to innerText, textContent returns all of the whitespace, as if the content were in a set of pre tags.

$(function() {

The above code would output the following to the console:

			Row One Item One
			Row One Item Two
			Row Two Item One
			Row Two Item Two

As you can see in the above example, textContent returned even the white space of the table row indentation. When using textContent to set the content of an element, anyy HTML markup in the string is output as text. This is different from what innerHTML does. This is great if you want to prevent malicious script injection in your app. Here’s an example of how textContent handles markup passed in as a string:

$(function() {
    var text = "<a href='#' onclick='doEvilThings()'>Please click here</a>";
    $("p:first-of-type").textContent = text;

This gets output as:

<a href='#' onclick='doEvilThings()'>Please click here</a>

Instead of something like this: Please click here

As you can see, the malicious code has been rendered as plain text. Life is good when the bad guys lose.


This method removes any white space at the beginning and end of a string.

		<li>item 1</li>
		<li>item 2</li>
		<li>item 3</li>
		<li>item 4</li>
		<li>     item 5     </li>
$(function() {
    // Will return: "item 5" with no white space.
    var text = $("p:last-of-type").text().trim();

Update Nov 19, 2010

As of version 1.0.7, ChocolateChip has two new methods for capitalizing strings: String.capitalize() and String.capitalizeAll(). String.caplitalize() capitalizes the first letter of the string, regardless of whether it has multiple words. String.capiatlizeAll() capitalizes the first letter of every word in the string. Here how you use them:

var sstr = "this is a string";
console.log(sstr.capitalize()); // => This is a string
console.log(sstr.capitalizeAll()); // => This Is A String

As of version 1.3.0, the following method is available:


In general, string concatenation is not very performant in JavaScript. However, using the Array.join method creates a string from an array very efficiently. $.concat() uses arrays or array like objects to perform efficient string concatenation. You pass an array of strings as the argument.
If you have an array-like object, you can convert it to an array using $.slice() (see example below).

var users = ["<li>Item One</li>","<li>Item Two</li>","<li>Item Three</li>","<li>Item Four</li>","<li>Item Five</li>"];
users.prependTo("#users > ol");
// Get the arguments object to prepend:
function outputString(){
    var str = $.slice(arguments);
outputString("This"," ","is"," ","a"," ","tedious"," ","example",".");

Insert Whatever, Wherever You Want

Leave a comment

ChocolateChip simplifies inserting content into a document

DOM level 3 has some new ways of injecting content into a document. And on top of that ChocolateChip has its own handy utility methods for inserting content. Here’s the goods:

  1. Element.insertAdjacentText()
  2. Element.insertAdjacentHTML()
  3. Element.insertAdjacentNode()
  4. $.make()
  5. Element.insert()
  6. Element.before()
  7. Element.after()
  8. Element.fill()
  9. Element.prepend()
  10. Element.append()

All three of the insertAdjacent methods take two parameters, the place to insert and the content to insert. Passing in the correct parameter for position is very important for getting your content where you want it. This means that these insert methods do not replace the contents of the element with the content you pass in. Instead they insert it in juxtaposition to the element. You have four options for where you want to insert. IMPORTANT! These arguments must be in quotes or you’ll get an exception.

This inserts the content immediately before the element so that the content become the previous sibling of the element.
This inserts the content into the element as its first child. This does not replace any other content already in the element.
This inserts the content into the element as its last child. This does not replace any other content already in the element.
This inserts the content immediately after the element so that the content become the next sibling of the element.


This method insert a string of text at the location passed in.

<p id="description">This is the main section.</p>
$(function() {
	$("#description").insertAdjacentText("beforeBegin", "This is before the description: ");
	$("#description").insertAdjacentText("afterBegin", "This is at the beginning of the description: ");
	$("#description").insertAdjacentText("beforeEnd", "This is at the end of the description: ");
	$("#description").insertAdjacentText("afterEnd", "This is after the end of the description: ");


This is similar to the Element.insertAdjacentText() method, except that it creates HTML which it then inserts at the specified locations.

$(function() {
	$("#description").insertAdjacentHTML("beforeBegin", "<p>This is before the description: </p>");
	$("#description").insertAdjacentHTML("afterBegin", "<p>This is at the beginning of the description: </p>");
	$("#description").insertAdjacentHTML("beforeEnd", "<p>This is at the end of the description: </p>");
	$("#description").insertAdjacentHTML("afterEnd", "<p>This is after the end of the description: </p>");	


Like the previous two methods, this method inserts content into the designated locations, except that it uses existing nodes. You could pluck nodes from elsewhere in a document, or create them on the fly for inserting.

$(function() {
	var a1 = $.make("<p>First Paragraph</p>");
	var a2 = $.make("<p>Second Paragraph</p>");
	var a3 = $.make("<p>Third Paragraph</p>");
	var a4 = $.make("<p>Fourth Paragraph</p>");
	$("#description").insertAdjacentElement("beforeBegin", a1);
	$("#description").insertAdjacentElement("afterBegin", a2);
	$("#description").insertAdjacentElement("beforeEnd", a3);
	$("#description").insertAdjacentElement("afterEnd", a4);	


$.make() is a method for creating HTML element nodes on the fly. It takes as its argument a string of valid markup. This must be correct syntax for the doctype used by the target document or the browser will not render it properly.

$(function() {
    var content = $.make("<p>This is a paragraph with some <strong>important</strong> and <em>trivial</em> information.</p>");
     var menu = $.make("<ul id="menu"><li>Item One</li><li>Item Two</li><li>Item Three</li></ul>");


The method does what the label say. It allows you to insert content into another element. The first argument is the content to insert. The second, optional argument is the position at which to insert the content. If no position is supplied it default to inserting the content at the end. As a convenience you can pass in “first” or “last” for a position. Otherwise a digit starting from 1 to indicate the position at which to insert. 1 is equivalent to “first.” If the numerical position passed as an argument is larger than the number of child nodes in the target element, it will be inserted in the last position. If the content passed in is a string, the method attempts to convert it into HTML nodes before inserting. If the content consists of HTML nodes, the method inserts them at the indicated position.

$(function() {
    // Insert this at the beginning:
    $("#response").insert("<p>A new paragraph.</p>", "first");
    // Insert this at the end:
    $("#response").insert("<p>Another paragraph at the end.</p>", "last");
    // Insert this at position 5, that is, as the fifth child of the element:
    $("#response").insert("<p>An important update.</p>", 5);


This method inserts content before the target element. The inserted content thus becomes the target’s previous sibling. The content passed in can be a node or an array of nodes.

$(function() {
     var newNode $.make("<h1>An Important Announcement</h1>");
    $("body > p").before(newNode);


This method inserts content after the target element. Thus the content becomes the next sibling of the target. The content passed in can be a node or an array of nodes.

$(function() {
     var newNode $.make("<li>The last item is always the most important!</li>");


This method replaces the contents of the element with the content passed as an argument. Unlike other methods above, this method does not attempt to convert a string into HTML before insertion. Rather it is primarily for replace the text content of an element with the text passed in. However, if a node is passed it, it will insert it into the element. This method always replaces whatever the content of the element is, even if that consists of multiple child nodes.

$(function() {
    $("#update").fill("This page has just been updated");


As of version 1.1.9 ChocolateChip offers the element.prepend method. This allows you to insert content at the beginning of a collection of nodes. If the parent is empty, the content will simply be inserted. This is just a convenience method to mimic the jQuery equivalent.

$(".menu").prepend("<li>item 1</li><li>item 2</li><li>item3</li>");


As of version 1.1.9 ChocolateChip offers the element.append method. This allows you to insert content at the end of a collection of nodes. If the parent is empty, the content will simply be inserted. This is just a convenience method to mimic the jQuery equivalent.

$(".menu").append("<li>Final item here</li>");

Adding Some Class to Your Document

Comments Off on Adding Some Class to Your Document

ChocolateChip provides several methods working with classes

  1. Element.hasClass()
  2. Element.addClass()
  3. Element.removeClass()
  4. Element.toggleClass()


Sometimes you just need to check an element to see if it has a class or not. To accomplish this use the Element.hasClass() method like this:

$.ready(function() {
    // We want the third paragraph in the document:
	var p = $("p:nth-of-type(3);
	if (p.hasClass("important")) {
		p.fill("This is very important!");
	// Get all list items and check to see if they have the class "medium":
	$$("li").forEach(function(item) {
		if (item.hasClass("medium") {
			item.css("font-size: 14px");
		} else {
			item.css("font-size: 20px");


This method does what the label says, it adds a class to the element:

// Here we're getting the all the list items of the second ul in the docuemnt:
$$("ul:nth-of-type(2) > li").forEach(function(item) {


Use the Element.remove() method to, well, remove a class:

$.ready(function() {
	$$("a").forEach(function(link) {
		if (link.hasClass("external")) {


And now, the best of all, the class toggler method. This method works differently depending on whether you pass in one or two classes to toggle. If a single class is passed, toggleClass() will add the class if the element doesn’t have it, or remove it if the element already has it. However, If you pass in two classes, toggleClass() will check the element to see if it has the first class. If it does, it will remove that class and added the second class. If the element doesn’t have the first class, toggleClass() will added it. Then the next time toggleClass is called, it will toggle the two classes on the element.

$.ready(function() {
	$$("li").forEach(function(item) {
		item.bind("touchestart", function() {
		item.bind("touchend", function() {
	$$("a").forEach(function(link) {
		link.bind("touchstart", function() {
			link.toggleClass("touched", "untouched");

Getting and Setting an Element’s Style

Comments Off on Getting and Setting an Element’s Style

ChocolateChip version 1.1.7

CSS() update

As of version 1.1.7 element.css() has been updated to accept arguments more like jQuery. You no longer need to enclose a string of CSS declarations in curly braces. You can just quote the string. This means that if you have code written with curly braces on for element.css() you’ll need to update that code to work with this version. You can also pass element.css() and object of property/value pairs. When passing an object, if the property is a single word, it does not need to be quoted. If it is a hyphenated property it does need to be quotes. The property values always need to be quoted. Observe the examples below:

// Example of string:
$(".content").css("height: 100%; width: 100%, background-color: #ccc; color: #666; border: solid 2px #666;");

// Simple property and value (can only use once, for more use object notation)
$(".menu").css("border", "solid 1px red");

// Passing in an object of properties and values:
$(".footer").css({height:"100px", width:"100%", color:"#000","background-color":"#fff});

// To get a particular style attribute of an element:
var menuFontColor = $(".menu > li").css("color");

Update Dec 23, 2010

As of version 1.0.8, ChocolateChip no longer has a separate $.style() method. Its functionality has been incorporated into the Element.css() method. The new functionality is explained as follows:

To get the style of an element, simply pass the css() method the property whose value you want:

console.log("The font size is: " + $("#item").css("font-size"));

Note: When ChocolateChip returns a CSS value, this is always a string. This is so even when it appears to be a numerical value such as height or width. To do any math operation with these types of returned values, you’ll need to convert them to numbers. You can do this with parseInt. If you do not use parseInt, your attempts at addition will instead result in string concatenation. The example below shows how to use parseInt with a returned CSS value to get the numerical equivalent.

var itemWidth = $("#item").css("width");
itemWidth = parseInt(itemWidth);
var distance = itemWidth + $("#item").getLeft();
console.log("The total distance from the left is: " + distance);

There are two ways to set styles on an element. You can set a property/value pair or a string of values delimited by curly braces and quoted. By enclosing the curly braced text we can pass in the complex CSS definitions as a string. At parse time, ChocolateChip removes the curly quotes and applies the CSS definition to the element:

// Example of property/value pair:
$("p:first-of-type").css("color", "red");

// Example of string enclosed in curly braces and quotes:
$$("li.members").forEach(function(members) {
   members.css("{ color: red; background-color: orange; font-size: 24px; font-weight: bold; }");

For versions 1.0.7 and earlier ChocolateChip uses the following two methods to get and set styles:

ChocolateChip has two methods for dealing with style. They are:

  1. $.style()
  2. Element.css()

$.style() takes two arguments: the element whose style you want, and the style you want:

$.ready(function() {
	var p = $("p:first-of-type");
	var pColor = $.style(p, "color");
	console.log("The text color is: " + pColor);

Setting an element’s style is easy using the Element.css() method. This method takes as its argument any valid CSS property/value pairs. By default this method adds the CSS to whatever is already defined on the element. If you want, you can pass an option second parameter of true. This will force the method to replace whatever inline styles the element might have with the styles you are passing in.

$.ready(function() {
	var p = $("p:first-of-type");
	var styles = "font-weight: bold; background-color: red; color: gold;";
	// This will append the new CSS onto the paragraph tag.
	// In contrast, this will replace whatever other styles might be inline on the paragraph with the styles being applied.
	p.css("font-size: 24px; text-shadow: 0 1px #fff; color: #000;", true);

As you can see in the above examples, you can assign the CSS to a variable and pass that in, or you can define the CSS in the method itself, your choice.

Attack of the Clones

Comments Off on Attack of the Clones

Cloning Nodes is Legal!

ChocolateChip provides several methods for dealing with nodes. These are:

Makes a copy of the element.
Deletes all of an element’s child nodes.
Deletes an element.
Wraps an element with the supplied markup.
Removes the markup containing an element, leaving the element in the document.
Replaces one element with another.



The Element.clone() method creates a copy of an element. If a boolean value that evaluates to true is passed, the element will be copied along with all of its child nodes. And if a false value is passed in, the method copies only the element, ignoring its child nodes.

<p>This is a paragraph.</p>
$.ready(function() {
    // This will clone the node with its child node, which is a text node.
    var p1 = $("p").clone();
    // This will output "This is a paragraph"
    // -1 will evaluate as a false boolean.
    // This will result in only the barebones p tag being cloned, not its content.
    var p2 = $("p").clone(-1);
    // This will not output anything since p2 has no child nodes.


The Element.empty() method will delete all child nodes from the element

<p>This is a paragraph.</p>
$.ready(function() {
    // This will remove the text from the above paragraph.


This method completely deletes a node from the document. Before deleting the element, it sets any events on the element to null. If you know what events you have bound on that element, you should probably use the Element.unbind() method to remove them before removing the element. That way your events are completely eradicated.

<p>This is a paragraph.</p>
$.ready(function() {
    // Delete the above paragraph from the document:


The Element.wrap() method wraps the element in the supplied markup. This is similar to the outerHTML method, except that it outputs true DOM nodes. In order to accomplish this, the method clones the node along with all of its children. It then creates the new markup to wrap around the node and inserts the node inside of the new markup. Then it replaces the node in the document with this newly wrapped node. This means that if you had bound and events to the original node, you will need to reattach them after wrapping. If you intend to do a lot of wrapping/unwrapping, and maintain event binding, then you should use event delegation by bind the events to the parent of the elements you intend to wrap or unwrap and capture the events during the bubbling phase. See the entry “Handing Events” for examples of this technique.

<p>This is a paragraph.</p>
$.ready(function() {
    // This will wrap the above paragraph in this div tag:
    $("p").wrap("<div id="paragraphWrapper"></div>");


The Element.unwrap() method removes the parent element from an element. To do this, it clones the node, then replaces the parent node with the cloned node. As with the Element.wrap() method, any bound events will be removed, but you can use event delegation to avoid this problem.

<div id="paragraphWrapper"><p>This is a paragraph.</p></div>
$.ready(function() {
    // This will remove the div surrounding the above paragraph:


The $.replace() method replaces one element with another. The first argument is the element you want to replace with. The second argument is the element you want to replace. As with the Element.wrap() and unwrap methods, any bound events will be removed, but you can use event delegation to avoid this problem.

<p>This is a paragraph.</p>
$.ready(function() {
    var divTag = $.make("<div id="replacementNode">A new div here.</div>");
    // This will replace the p tag with the newly created div tag:
    $.replace(divTag, $("p"));

Ajax and JSON

Comments Off on Ajax and JSON

ChocolateChip provides method for AJAX updates and JSON data binding.

A method to perform basic HttpRequests
A method to perform JSON data binding.



The Element.xhr() method provides a way to update parts of a document with dynamic content pulled from another external document. This would normally involve document fragments, but could also be a complete document, depending on what your needs are. The If no parameters are passed, the Element.xhr() method replaces the content of the target element with the content of the requested document.

<p id="update">Old text here.</p>
$(function() {
    // This will replace the content of the paragraph above with the content of the requested document.

The Element.xhr() method can also receive and object literal of options to execute depending on the success of the HttpRequest. These are successCallback and errorCallback. The successCallback allows you to do something after the successful insertion of the new content. The errorCallback allows you to do something when HttpRequest fails. You can provide both, either one or none. Here’s an example of how to provide for both:

<p id="update">Old text here.</p>
<p id="update-message"></p>
$(function() {
    /* 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 successCallback, and if it is not, it will execute the errorCallback.
    $("#update").xhr("../data/newUpdate.html", {
        successCallback: function() {
            $("update-message").text("The update was successful!");
        errorCallback: function() {
            $("update-message").text("There was a problem retrieving the requested file.");


The Element.xhrjson() method provides a way to do rudimentary data binding with JSON. You do this by passing in the URI for the JSON document you want to bind to, followed by an object literal that defines which elements of your document get mapped to which values of the JSON object. The JSON document can be created and updated dynamically on the server. That way, each time your document requests it, the bound elements in your document will be updated with the current data. It’s a good idea to have some default values in your document in case there is a problem retrieving the JSON fie.

In the example below, we are binding JSON values to the corresponding element ids in a document:

Here is a json data file named data.html:

	'firstName': 'Robert',
	'lastName': 'Biggs',
	'role': ' and the author of ChocolateChip', 
	'job': ' front-end developer'

Here is a section of HTML with some default values that we wish to replace with the values from the json file:

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

And here’s the JavaScript to get the JSON file using $.xhrjson():

$(function() {
    $("#content").xhrjson("data.html", {
            "firstName": "#firstName",
            "lastName": "#lastName",
            "job": "#job"

Update Nov 19, 2010

As of version 1.0.7, ChocolateChip has a $.template() method for allowing quick and simple JavaScript-based templates on the client side. This is basically a repurposing of John Resig’s ( JavaScript Micro Template framework. It’s a very small amount of code that provides the ability to create complex templates with ease.

Here’s an example of a typical template:

<script id="template_1" type="text/jsmt">
		<% for (var i = 0; i < users.length; i++) { %>
			  <p>Name: <strong><%= users[i].fname %></strong> <em><%= users[i].lname %></em></p>
		<%  } %>
<div id="template_1_output"></div>

First thing, notice that the JavaScript template is inserted where it the data will be output. This is not a requirement. The template can be anywhere in the document. It doesn’t matter. What matters is that the script have a unique ID so that you can get it through a DOM query and that it have a special MIME type, which is “text/jsmt.” Jsmt stands for JavaScript Micro Template, obviously there is no browser that knows what a script of type jsmt is, so browsers don’t know how to parse and display the contents of the script tag. That means none of the html will be rendered. This is not a bug in browsers, this is how they are supposed to function. If you look at the contents of the script tag you will see we have some HTML tags for defining the template’s structure and we have JavaScript enclosed in and tags. The first set, is for normal JavaScript code. The second set of tags, is used for processing a variable in the template. If you’ve used ASP or JSP in the past, you will recognize these tags.

After the $.template method processes the script tag, it outputs the result. It’s your job to decide where you want to output the result to. You can store it in a variable and out put it later, or immediately. So, from our previous example, to process the template, we use the $.template() method:

   // Process the template of ID "template_1" with JSON data in the variable "data".
    var r = $.template("template_1", data);
    // insert the results of the parsed template into the div with id "template_1_output."

We could also perform conditional checks inside the tags before outputting the data:

<script type="text/jsmt" id="jsmt_list_items">
	<% people.each(function(name) {
                // Only output names with a y in them:
		if (/y/.test(name)) { %>
		<li><%= name %></li>
	 <% }
	}); %>

Update Dec 23, 2010

As of version 1.0.8, ChocolateChip offers two methods to enable the HTML5 dataset API for browser versions that support it. For those that do not it has a fallback using normal DOM get and set attribute methods.
A method add or retrieve dataset values
A method to remove a dataset from and element.

According to the dataset API in HTML5, any element can have datasets indicating information relative to that element. a dataset value always begins with “data-“. Here’s and example of an element with datasets:

   <li data-first-name="John" data-last-name="Doe" data-occupation="teacher">John Doe<li>
   <li data-first-name="Sam" data-last-name="Smith" data-occupation="doctor>Sam Smith</li>

Using we can get any of the dataset values in this way:

console.log("John's occupation is: " + $("li:first-of-type").data("occupation"));

Similarly, we can set a dataset value as follows:

(function() {
   var personnelHeight = [ "5f8n", "5f10n", "6f0n" ];
   var heightnum = 0;
   $$("li").each(function(item) {"personnel-height", personnelHeight[heightnum]);

To remove a dataset, use the Element.removeData() method:

(function() {
   $$("li").each(funciton(item) {
      item.removeData("first-name"); /* Removes data-first-name from each list item. */

Special Tools for Special Needs

Comments Off on Special Tools for Special Needs

ChocolateChip has several utility methods that enable you to do useful things. These are:

This method can take two arguments: the object to extend and the properties to extend it with. If only properties are passed, they are added directly to the $ object to extend ChocolateChip itself. The properties are passed as an object literal of key/values pairs.
This method imports the indicated script into the document by attaching it to the head tag. It accepts a valid URI to the script.
If the mobile browser is not in standalone mode, meaning that the user has not yet installed the Web app on a mobile device, this method hides the browser address bar by slightly scrolling the page to force the addressbar out of view. Until the user actually adds the mobile Web app to the mobile device, this method will help make the online browser use of the Web app feel mofe like an installed app.

Using $.extend()

	growl : "Woof!",
	bark : function(msg) {
		if (!msg) {
			msg = this.growl;
$(function() {
	$.growl = "Bow wow! Bow wow!";
	/* This outputs:
	Bow wow! Bow wow!

Using $.importScript()

If you need to dynamically import a script for whatever reason, you can use this method to do so. It inserts the script into the head tag, at which point the browser immediately parses the scripts and executes it. Simply pass in a valid URI for the script:

$(function() {

Using $.hideURLbar()

You want to execute the $.hideURLbar() method whenever the user does something that might cause the browser addressbar to remain in view, such as when the user navigates to annother page, or when the user changes the orientation of the device. To hide the addressbar, simply invoke the method after whatever code might cause the scrollbar to appear:

$(function() {
	$("#aboutButton").bind("click", function() {
		/* This code adds a class to the about panel, causing it to slide into view. */
		// After scrolling the panel into view, make sure the addressbar is not showing.

From version 1.0.7, ChocolateChip offers the following four methods: $.delay(), $.defer(), $.enclose(), and $.compose().


This method enables the delayed execution of a function. $.delay() takes two arguments, a function and an integer indicating how long to wait before executing the function:

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


The $.defer() method cause the execution of a function to wait until the callstack is clear. This means that regardless of where this is in a block of code, it will be executed after all other code.

 $.defer(function() { 
     console.log("This will be executed after all the other code."); 
console.log("This will be executed before the code before it."); 


This method enables you to enclose a method inside another method so that you can do something before and after the enclosed method’s execution. It takes two arguments, the function to enclose and the function that encloses it. Below you can see that the function “hello” gets passed in the the enclosing anonymous function as the term func, which allows us to envoke it as func(“Stan”) with concatenation before and after it:

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.";


This method enables the ability to pass one function as an argument of another, building up a chain of passed function arguments. When multiple functions are passed as arguments, they are passed in as arguments from the right to the left, so that the last argument becomes the argument for the function preceding it, etc.

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.

Besides these, there are a couple of others. First off, ChocolateChip automatically outputs a class of “portrait” or “landscape” on the body tag when the mobile device’s orientation changes. You just have to write your CSS to be aware of that. Something like this would work:

body.portrait > article {
	background-color: green;
	color: red;
body.landscape > article {
	background-color: red;
	color: green;

Customize the aliases for ChocolateChip

In case you are really, really want to use some other library with ChocolateChip, and you’re using one that also uses $ and $$, ChocolateChip will automatically reassign its $ and $$ methods to __$ and __$$ respectively. If you don’t want to use these either, you can assign them to whatever other aliases you wish. To make this all work, though, you’ll need to import the other library before ChocolateChip, otherwise ChocolateChip will clobber the $ and $$ of the other library. To reassign the default ChocolateChip aliases, do so in a $.ready block as follows:

<script src="someOtherLibrary" type="text/javascript"></script>
<script src="chocolatechip-1.0.6.js" type="text/javascript"></script>

<script type="text/javascript">
$(function() { = window.__$;
    window.CC = window.__$$;
    // Now you can use cc and CC for ChocolateChip's $ and $$ while using the $ and $$ of the other library.


If you change the reference to $ and $ and you have any external ChocolateChip scripts that use $, you will need to update those as well or you’ll get an error because $ and $$ will not point to the ChocolateChip versions. Although you can change ChocolateChip’s global alias to whatever you want, ChocolateChip will continue to use $ internally.

Device detection

ChocolateChip also provides a number of device tests so that you can write custom code for different devices. The test return true or false. Here is what’s available:

  1. iphone
  2. ipad
  3. ipod
  4. android
  5. webos
  6. blackberry
  7. online
  8. standalone

Here’s an example of device detection:

if (!$.iphone) {
	alert("This app only works with the iPhone.");
if (!$.standalone) {
	alert("Please install this app on your homescreen by pressing the plus icon in the toolbar below.")
if (ipad) {

Update Dec 23, 2010

As of version 1.0.8, ChocolateChip offers the following two methods:

A method get the offset top of an element relative to the document’s top.
A method to get the offset left of an element relative to the documents left.

These two methods return their position as integers without any length identifiers:

var elem = $("#favItem");
var elemPos = "top: " + elem.getTop() + "px; left: " + elem.getLeft() + "px;";
console.log("The element's position is: " + elemPos);

New in version 1.2.0:

Object Extension:

Just as you can use forEach() or each() on an array, ChocolateChip also provides a convenient way to iterate over an object using Object.each(). Like each() on an array, you can access the key and value of the object. As with the array version, you can name these two arguments whatever you want. The first argument will always be the key and the second, the value”

var obj = {"i-1": "item 1", "i-2":"item 2", "i-3":"item 3", "another-one":"item 4", "something-else":"item 5"};
obj.each(function(key, value) {
    $("ol").append("<li>" + value + "</li>");

This will output:

   <li>item 1</li>
   <li>item 2</li>
   <li>item 3</li>
   <li>item 4</li>
   <li>item 5</li>

Older Entries Newer Entries