Why ChocolateChip?

Comments Off on Why ChocolateChip?

Because it’s small and tastefully efficient.

There are already so many JavaScript frameworks out there. These are designed especially for desktop Web development by eliminating for the end user the myriad of browser quirks and differences. It’s hard to imagine doing desktop Web development without using one of those libraries There are also a number of frameworks designed for mobile Web development. The funny thing, though, is that they use desktop frameworks with add ons for mobile Web development. After using several of these and noticing how much unnecessary baggage was there because of the desktop heritage, I decided to create a framework that was specifically optimized for mobile Web app development. ChocolateChip has no desktop baggage. It has nothing, zero, zilch, nada in it for IE, Netscape Navigator, nor 1 .x or 2.x versions of desktop browsers. ChocolateChip instead utilizes the features available in the modern mobile browser engines used in iPhones, iPads, iPods and Android devices. We’re talking Webkit here, and that’s a good thing.

You know what I’m talking about, like when you want the first or next sibling element and you get an empty text node, or not, depending on the browser. ChocolateChip uses DOM level 3 methods, objects and properties to make DOM traversal easy. I know, you’re going to ask about the selector engine. We don’t need no stinking selector engine. Waste of code. I feel like laughing when I read that a framework’s selector engine is being updated to work with mobile. I have to repeat this, you don’t need a selector engine. You have something better that’s built in. That means it is faster than any selector engine could ever possibly be. It’s called querySelectorAll. It takes as its argument a valid CSS3 selector. Because ChocolateChip uses the browser’s native querySelectorAll feature, you can get elements in this way:

var firstPara = $("#intro p:first-child");
var para5 = $("section > p:nth-child(5)");
var evenItems = $$("li:nth-child(even)");
var externalLinks = $$("a[href$='.php']");

As you might have noticed, the markup looks like jQuery or Prototype. This is on purpose. ChocolateChip has two way of getting nodes. When you want to get a single node, you use the $() method. This will always return the first instance of the selector supplied. When you want to get a collection of nodes, you use the $$() method. This returns a collection in the form of an array, even if it has only one member. jQuery rolls the functionality of this method into the $(), whereas Prototype and Mootools keep them separate. After a lot of consideration, I decided to keep them separate. I didn’t want to do looping on collections behind the scene. I want you, the developer to know what’s going on with your code. The goal of ChocolateChip is to eliminate as much obfuscation as possible.

jQuery wraps everything up in the jQuery object, requiring that you use only jQuery methods on all returned nodes. ChocolateChip returns either a single node or, in the case of a collection, an array of nodes. This means that you can use normal JavaScript on everything that ChocolateChip returns. So, if you decide that you don’t want to use a ChocolateChip method, you can use whatever JavaScript you want to write and mix it in wherever you want with standard ChocolateChip methods.

Rather than writing methods to implement missing features in browsers, I use the native methods already implemented in Webkit. And, although my goal was to make a framework for mobile Webkit, it also works without modification on desktop versions of Safari, Chrome, Firefox and Opera. And as far as IE goes, you can forget everything before IE9.

But then, that’s the whole point. ChocolateChip was not written for desktop browsers, it was written for mobile browsers. If it happens to work for desktop browsers, fine. I will not, however, add code to ChocolateChip just to make it useable for desktop development. That’s not its purpose. Yet I will be looking to see what I can add to ChocolateChip to enhance its usefulness for mobile Web app development.

Because ChocolateChip’s purpose is for mobile, size is of supreme importance. To restrain it’s size as much as possible, I was forced to limit what I put in it. Due to the memory constraints of mobile Web app development, having a smaller framework means having more memory for the content in your app. Running out of memory will cause the mobile browser to crash. Do you follow what I’m saying? You want that framework as small as possible. And ChocolateChip fits the bill well. It’s just 8k when minified.

But if you are really determined to eat up valuable browser memory by using some other framework that also uses $ and $$, you can customize ChocolateChip to use whatever you want as an alias. If $ and $$ are already in the global name space, ChocolateChip will assign its versions of these to __$ and __$$. This is indicated below:

if ((!window.$) && (!window.$$)) {
	window.$ = $;
	window.$$ = $$;
} else {
	window.__$ = $;
	window.__$$ = $$;
}

In such a case, you can reassign __$ and __$$ to whatever other aliases you want to use. You would do this at the start of you own document inside the $.ready() block:

$.ready(function() {
	window.choco = window.__$;
	window.chocos = window.__$$;
});

This allows you to write choco("p:first-child");.

ChocolateChip is available in three flavors, dark (with full comments), regular (with comments removed) and light (minified). If you’re new to ChocolateChip, by all means download the dark version. Crack it open and read the comments. They explain each method, what arguments they take, what they return, syntax, examples, etc. If you’re in development and you want to be able to troubleshoot exceptions in your browser’s Web inspector, you probably want to use the regular one. And when you’re ready to go into production, you want to switch over to the light version. You can get them all from ChocolateChip’s online GitHub repository.

To see examples of what ChocolateChip can do, visit http://www.css3wizardry.com. That site has numerous posts about how to built out various mobile Web controls that work like native controls on the iPhone, iPad, iPod and Android platforms.

Advertisements

Getting Stuff with $() and $$()

Comments Off on Getting Stuff with $() and $$()

Before you do anything, you need to find out if the browser is ready for you

Whenever you want to write some code with ChocolateChip, you need to check to see if the browser has finished parsing the document so that you can get nodes. ChocolateChip makes this possible with the $.ready() method. Here is an example of how to wrap your code in the $.ready function or $(function() {}):

$.ready(function() {
    // Your code goes here.
});

Whatever code you put inside the ChocolateChip ready function will not execute until the document is ready for it. It’s just like jQuery’s $(document).ready(function() {}), or any other framework’s DOMready method. Except that you don’t have to pass in the document as an argument. $.ready() straightaway checks to see when the document is ready. What else would you be waiting for?

So, $.ready() takes one argument, a function to execute when the document is ready. To get your script to execute, you can pass in a predefined function that you’ve defined elsewhere:

var doSomething = function() {
    console.log("This is doing something. Cool, huh?");
};
$.ready(function() {
    doSomething();
});

This works fine. However, in most cases you’ll want to write code blocks inside an anonymous function that is defined directly within the parentheses of the $.ready() function. This isolates your code inside the $.ready() function to avoid namespace collisions with any other code you might have elsewhere:

$(function() {
    var logSomething = function(msg) {
        console.log(msg);
    };
    logSomething("I hope this is working properly.");
});

You can also access the window and document objects with $, and if you pass no selector to $, it will by default return the document object. Please note that although you can access the window and document objects, they do not have the same interface as DOM nodes and therefore most of those methods will not work on the window and document objects.

var windowHeight = $(window).outerHeight; // returns the height of the window frame
var docSource = $(document).title // returns the title of the document
var docSource = $().title // same as above.

All ghosts of selector engines be gone!

Selector engines are now so out of fashion. Why does anyone seriously think they need one when we have querySelector and querySelectorAll? These both take as their argument a valid CSS3 selector. You can’t get any simpler than that. It’s built into the mobile browser too. It’s a complete no-brainer, right?

ChocolateChip uses querySelector and querySelectorAll to return matching nodes in your document. To get a single node is really easy. Just invoke the $() method.

$(function() {
    var elem = $("#menu > li:last-of-type > a");
    elem.css("border-bottom: solid 2px blue");
});

No rocket science here. Just describe what element you want using CSS3 selectors and, bang! You’ve got it and can do stuff. Here I’m using ChocolateChip’s css() method to add inline CSS on the anchor tag in the last list item in a container with an id of “menu.” Bare in mind the the $() method uses querySelector. This means it always returns a single node. If there are multiple matches, $() will return the first match. However, with the power of CSS3 selectors you can craft a selector to pick out the node you want with surgical precision without having to loop through a collection.

OK, now let’s get a little complicated here. If I use $$() to search a document for multiple matches, I get back what’s called an HTML collection. The $$() method turns that collection into an array so that we can do something practical with it:

$(function() {
    $$("#list > li").each(function(item) {
        item.css("background-color: red");
    });
});

So, to clarify what’s going on, when ChocolateChip finds a number of matches for a query, it takes that HTML collection and turns it into an array. Since it returns an array, you can use the forEach method. As a matter of fact you can use any of the array methods you want. In most cases, though, you’ll want to use the forEach method. This takes as its argument a function to execute on each index of the array. This function can take an argument of an object using any name you want to indicate the value of “this” during execution of the function. During the execution of the function, “this” will refer to that particular index of the array. In the above example of code, I get an array of list items. To operate on each list item I use the term “item” as the argument of the method being executed by forEach. You can use whatever term makes sense for the individual members of the array. The nice thing about this is that it makes your code more readable, and that makes your code easier to maintain and easier for other people to use as well.

Danger! Will Robinson, danger!
I could have rolled the two selector methods together. Actually, at one point I did. But that led to several problems. It was crazy trying to decide when to return a single node and when to return a collection. And how to know if the user intended to get a single node or a collection. Rather than writing a mess of code to deal with all the edge cases, I decided that for simplicity and sanity I would keep the two method separate. jQuery handles this problem eloquently by wrapping everything in the jQuery object, where everything is hidden from the user. I did not want to go this route. I wanted everything to stay accessible JavaScript and no obfuscation.

Personally, I want to have a way to get a single node and deal with it as such, not as an object. I want to be able to get a node that I can use normal JavaScript on. I do not want a node wrapped in an object that forces me to use the framework’s methods instead of natural JavaScript methods. I thought long and hard about this and decided that it was better not to use object wrappers.

Besides, there was another reason I didn’t want to hide the looping from you. I wanted to give you the opportunity to choose how you operate on the array returned by $$(). Instead of using forEach(), you might want to use reverse(), sort(), indexOf(), lastIndexOf(), some(), every(), map() or filter(). Depending on your needs, these are all possible array methods that you could use on the array returned by $$(). If you’re a developer of any standing, you’re probably already familiar with these array methods from other programming languages. If you’re not familiar with them, you can read more about them here.

One more thing, don’t forget that if you want, you can use the DOM’s built-in querySelectors. Here’s an example:

// The querySelector method will return a single node:
var elem = document.querySelector("#menuList > li:first-of-type");
elem.style.backgroundColor = "red";

// The querySelectorAll method will return a nodeList, even if only one node is found:
var items = document.querySelectorAll("#menuList > li");
for (var i = 0, i < items.length; i++) {
    items[i].style.cssText = "font: bold 14px/20px Helvetica, Sans-serif;"
}

To see examples of what ChocolateChip can do, visit http://www.css3wizardry.com. That site has numerous posts about how to built out various mobile Web controls that work like native controls on the iPhone, iPad, iPod and Android platforms.

Find and FindAll

As of version 1.1.7 ChocolateChip offers element.find() and element.findAll() as ways to get nodes starting from a particular node. If you already have a node and one to get one or more of its descendants, you can use these methods. Element.find() is works like $() in that it returns a single node, and element.findAll() works like $$() in that it will return a collection.

Here’s an example:

var menu = $("#menu");
var firstMenuItem = menu.find("li");
menu.findAll("li").each(item) {
    item.css("background-color: yellow; border: solid 2px red;");
});

Getting in Touch with Your App

Comments Off on Getting in Touch with Your App

If you click me again, I’m going to get touchy!

So, you can tell when the document is ready for manipulation and you can get nodes in the document. You can probably use normal JavaScript to do interesting things with those nodes. But you’re missing one thing that people need in order to use your app. You need interaction. In other words, you need event handling. You need to know when the user interacts with your app. If you’re using ChocolateChip to develop a mobile Web app, you need to get a finger on touch events. Clicks are for people who have mice, or hamsters, or gerbils, or whatever. People with mobile devices are smearing their greasy fingers all over those devices. You want to be able to capture those smears and do something with them.

ChocolateChip provides two very simple ways to deal with events: bind and unbind. Bind is not a cross-browser workaround that tries to play nice with the browser from that company in Redmond. Bind is using the browser’s standards-based event listener. Because of this, you can bind multiple events of the same type with different blocks of code to execute and they will all fire, unlike the inline event handers. But enough with the explanations. Let’s look at some examples. We’re going to start with some markup which has buttons for navigation, etc. One thing, because you can bind events to any element, I see no reason to use link tags to create buttons. I just hate having to do the return false thing to cancel the href attribute on a link. You can use a div or a span to make your button, and you don’t have to worry about canceling the href attribute or getting rid of the link’s default text underline on hover. The whole idea of ChocolateChip is how to get by with less. With that in mind, here’s my minimalistic markup for a navigation bar:

<article>
	<section>
		<header>
			<span class="button goHome">Back</span>
			<h1>Interface</h1>
			<span class="button about">About</span>
		</header>
		<nav>
			<ul class="list drilldown">
				<li rel="#RadioButtons">Radio Buttons</li>
				<li rel="#ProgressBar">Progress Bar</li>
				<li rel="#Tabs">Tabs with a Popup</li>
				<li rel="#Popup">Popup Window</li>
			</ul>
		</nav>
	</section>
</article>	

What we’re going to do with the buttons is just show how to bind touch events to handle touch interaction visually. In desktop browsers’ when the user’s mouse is over something with a hover state, the user is presented with a visual cue. Mobile devices have no mice, but your fat finger. Mobile devices do not have hover states, but using touch events we can indicate to the user that they’ve touched something by giving it a hover class. And when the touch ends, we remove the hover class. This gives the user the sense that he or she just interacted with your interface. Here’s the code to make that happen with the markup above:

$$(".button").each(function(button) {
    button.bind("touchstart", function() {
        this.addClass("hover");
    });
    button.bind("touchend", function() {
        this.removeClass("hover");
    });
})

Notice that we only need to get that collection of buttons once. Once we have it we can bind events for touchstart and touchend. Touchstart is like mousedown in a desktop browser, and touchend is like mouseup. When the user touches, we capture the event and invoke the ChocolateChip method addClass() to add a class of “hover” to the button. Similarly, when the user ends the touch, we remove the class hover using the ChococlateChip removeClass() method. In the above event handlers, “this” refers to the element being interacted with. Instead of adding and removing classes, you could write some other JavaScript code to do something to the objects referred to by “this.” The this keyword is the real Javascript keyword, not a framework specific reference wrapped in a framework object.

We could similarly add touch events to the list items in our markup. Here is the updated code:

$$(".button").each(function(button) {
    button.bind("touchstart", function() {
        this.addClass("hover");
    });
    button.bind("touchend", function() {
        this.removeClass("hover");
    });
});
$$(".list li").each(function(item) {
    item.bind("touchstart", function() {
        this.addClass("hover");
    });
    item.bind("touchend", function() {
        this.removeClass("hover");
    });
});	

We could also add some navigation to the list items by extending our touch event. We just need to get the rel attribute from each list item and direct the window location to it:

$$(".button").each(function(button) {
    button.bind("touchstart", function() {
        this.addClass("hover");
    });
    button.bind("touchend", function() {
        this.removeClass("hover");
    });
});
$$(".list li").each(function(item) {
    item.bind("touchstart", function() {
        this.addClass("hover");
        window.location = $(this.getAttribute("rel"));
    });
    item.bind("touchend", function() {
        this.removeClass("hover");
    });
});	

As you can see, with a few lines of code, ChocolateChip enables us to accomplish quite a lot. There’s no framework obfuscation going on. It’s human-readable as well as easy to maintain and extend.

Now if you’re a good developer, you know that when you’re done with doing things you need to remove your event handlers. You can do this with the unbind method. The unbind method is attached to the element upon which it fires, just like the bind event. Like the bind event, it accepts an event. It also needs the name of the function or method that the event was executing. Am I getting any raised eyebrows out there yet? OK, let me explain. If the function has no name, you can’t remove the event. What do all the above examples have in common? We’re binding events with anonymous functions. They’re called anonymous because they don’t have names. So, like I said, they can’t be unbound. If your app only has a few bound events, this probably won’t be a problem. If you have a lot of events, this will be a problem, especially if you adding and remove nodes with events attached to them. Not removing the events causes memory leaks, and these over time lead to the browser running out of memory, slowing down and eventually crashing.

To avoid this you have two choices, you can name your anonymous functions or you can do an event reset. One of the things developers love about anonymous functions is that you define them right where you’re executing them. Naming an anonymous function doesn’t mean you have to give up this freedom. Here’s the above code rewritten to use named functions instead of anonymous functions.

$$(".button").each(function(button) {
    button.bind("touchstart", function touched() {
        this.addClass("hover");
    });
    button.bind("touchend", function untouched() {
        this.removeClass("hover");
    });
});
$$(".list li").each(function(item) {
    item.bind("touchstart", touchedItem = function() {
        this.addClass("hover");
        window.location = $(this.getAttribute("rel"));
    });
    item.bind("touchend", untouchedItem = function() {
        this.removeClass("hover");
    });
});	

In the first each loop we bind the elements with named functions: touched() and untouched(). In the second each loop we set the anonymous functions to touchedItems and untouchedItems. Be aware that these functions now reside in the global space. If you wish to avoid polluting the global space with these functions, you can use a pattern of delegated events using event bubbling to capture the events at a higher level in the document. See the section on events for more details about this method of event capture.

Note:

One last thing, if you want to you can also add bindings for click events if you want to test your app in a desktop browser or if you want to make your Web app usable on modern desktop browsers as well.

If you are using ChocolateChip 1.0.7 or later you can also use event delegation as a way to track touch events.

Using $.ready() and $.loadEvent() to execute code

Comments Off on Using $.ready() and $.loadEvent() to execute code

ChocolateChip provides two ways of executing code: $.read() and $(function() {}). These are identical, in that they both execute code as soon as the browser has finished parsing the DOM but before it has visually rendered it to the screen. The advantage here is that you can do things with the document, such as hiding or showing or adding things, before it displays to the user. There is also the $.loadEvent() method waits until the document is completed loaded and output to the screen. This means the user first sees the document load, then sees whatever changes your code makes to the document. In most cases, doing document setup after page load is a bad experience for the end user because they have to wait twice, first for the page to load fully, then for you code to finish executing.

There is also a big difference in how these two methods handle code. In most cases you would pass in your code to $.ready() using an anonymous fuction like this:

$.ready(function() {
	$("#Home").addClass("current");
	$(".button").forEach(function(button) {
	    button.bind("touchstart", function() {
	    	button.addClass("touched");
	    });
	    button.bind("touchend", function() {
	    	button.removeClass("touched");
	    });
	});
});

We could just as well have defined our code outside the $.ready() block and called the functions inside it like this:


var setHomeCurrent = function() {
	$("#Home").addClass("current");
};
var setupButtons = function() {
	$(".button").forEach(function(button) {
		button.bind("touchstart", function() {
			button.addClass("touched");
		});
		button.bind("touchend", function() {
			button.removeClass("touched");
		});
	});
}:
	
$.ready(function() {
    setHomeCurrent();
    setupButtons();
});

The above block works, however, I strongly recomend you put as much code inside the $.ready() block in order to reduce namespace collisions. Putting all your code in the $.ready() block also makes it easier for you so find the code being executing.

The $.loadEvent is excatly like $.ready() or $(function() {}). The only difference is when the code gets executed. As I mentioned above, $.ready() executes code when the browser has finished parsing the document’s nodes. $.loadEvent executes code after the document and all of its resources have been full loaded and rendered to the screen. You can pass in functions to execute, or you can use and anonymous fuction block like $.ready() does to define all your code there. The $.loadEvent() chain loads your functions on to the regular window.onload event. By default you can only pass one fuction to the onload event. $.laodEvent gets around this by putting all the functions into an array and then executing the functions in the array sequentially. If you have several $.loadEvent() declarations in your code, the browser will execute them in the order in which they reside in the code being parsed. Here’s an example of the two ways to use $.loadEvent():


var setHomeCurrent = function() {
	$("#Home").addClass("current");
};
var setupButtons = function() {
	$(".button").forEach(function(button) {
		button.bind("touchstart", function() {
			button.addClass("touched");
		});
		button.bind("touchend", function() {
			button.removeClass("touched");
		});
	});
}:
	
$.loadEvent(function() {
    setHomeCurrent();
    setupButtons();
});

// Or you could code it this way:

$.loadEvent(function() {
	$("#Home").addClass("current");
	$(".button").forEach(function(button) {
	    button.bind("touchstart", function() {
	    	button.addClass("touched");
	    });
	    button.bind("touchend", function() {
	    	button.removeClass("touched");
	    });
	});
});

Like jQuery and Zepto, you can also user $(document.ready({}):

var doSomething = function() {
   console.log(&quot;This is doing something. Cool, huh?&quot;);
}
$(document).read(function() {
	doSomething();
});

You can also use the simpler and more convenient format of a ChocolateChip function:

var doSomething = function() {
   console.log(&quot;This is doing something. Cool, huh?&quot;);
}
$(function() {
   doSomething();
});

Handling Events

Leave a comment

ChocolateChip provides a number of methods for dealing with events. They’re listed blow:

Element.bind()
Binds a event and callback to an element.
Element.unbind()
Removes and event and its callback from an element.
Element.removeEvents()
Sets all events on an element to null.

Element.bind()

This method binds the event to the element it is called on. It takes two arguments: the event enclosed in parentheses and a function to execute when the event occurs.

$.ready(function() {
    $("#home").bind("touchstart", function() {
        window.location = "http://css3wizardry.com"; 
    });
    $$("li").forEach("touchstart", function(item) {
        $(this.getAttribute("rel")).addClass("current");
    }
    $$(".button").forEach("touchstart", function(button) {
        button.addClass("touched");
    });
    $$(".button").forEach("touchend", function(button) {
        button.removeClass("touched");
    });
});

Element.unbind()

ChocolateChip provides an unbind method for removing any events from an element. This is especially important to do before removing/deleting any elements from your document in order to prevent memory leaks. There also may be the rare case where you only want the use to be able to perform an action once. In such a case, you can execute your code and as the last step unbind the event.

To unbind and event you need to pass in two arguments: the event that was bound and the name of the function that it executed. That means that if you were binding events with anonymous function, you will be unable to unbind them. There are several ways to work around this. This first is to declare all your functions separately with proper names. Or you could simply provide a name for the anonymous function while you are passing it to the event. You can do this in two ways:

$.ready(function() {
    $$(".button").forEach("touchstart", function touchedButton(button) {
        button.addClass("touched");
    });
    $$(".button").forEach("touchend", untouchedButton = function(button) {
        button.removeClass("touched");
    });
});

In the above example we have provided our events with function defined as arguments, like anonymous function, but these are both named. In the first example it is a normal named function. In the second example it is an anonymous function assigned to the global variable “untouchedButton.” Actually, in both cases these functions now reside in the global space. They are not private. Note that in the second example you cannot use the keyword “var” to assign the anonymous function to a variable. This would result in a parse error. With these functions now named we could remove them when necessary.

$.ready(function() {
function unbindEvents() {
    $$(".button").forEach(function(button) {
        button.unbind("touchstart", touchedButton);
        button.unbind("touchend"), untouchedButton);
    });
}	
window.onunload = unbindEvents;
});

Element.removeEvents()

If you really like anonymous functions, but you want a way to negate your events at some point, there is another alternative. ChocolateChip provides a utility function that parses all events attached to an element and sets them to null. It’s easy to execute. Just call it on the element.

$.ready(function() {
    $$(.button).forEach(function(button) {
        button.removeEvents();
    });
});

Event Delegation with Event Bubbling

If you have a collection of elements that you want to bind events to, instead of binding the event to each element, it would be more efficient to use event delegation to capture the events at a higher level. For example, if you have a list and you want to attach events to each list item you could do as follows:

$.ready(function() {
	$$("ul#menu li").forEach(function(item) {
            item.bind("touchstart", function() {
                item.addClass("touched");
            });
        });
});

This is fine to do if you have a few list items, but if your list has many items and you have many such lists throughout your application, this is very inefficient. It eats up memory and slows down your app. On top of that, if the list items are dynamic, you would have to write some event listeners to rebind events to any new items added to the list. And easier way is to attach an event handler to the list itself and listen for events on the list items. This way each list has only one bound event and it doesn’t matter how many list items there are or if any are removed or added. The event on the list will always capture any interaction with its child elements. In order to know what child element was the receiver of the event, we use the DOM’s target property. We can check whether it is a list item or not and then define what we want to do with it. Here’s an example:

$.ready(function() {
    $$("ul#menu").bind("touchstart", function(e) {
         if (e.target.nodeName.toLowerCase() === "li") {
               e.target.addClass("touched");
         }
    });
});

So, in the above code, we check to see if the target is a list item. If it is, we add a class to it. This simple pattern can be used whenever you have a collection of elements that you need to attach events to. Remember, attach an event to the parent of the collection and check the target to see if it is the element type you are interested in. If it is, do what you need to with it. Because we’re checking for list items, when the e.target is equal to a list item, we use e.target as the reference to the list item we wish to attach the class to.

The following code has both methods: attaching events to every list item and listening for events on the list itself:

$.ready(function() {
    // In this example events are attached to each list item:
    $$("ul#menu li").forEach(function(item) {
        item.bind("touchstart", function() {
            console.log(item.innerText);
        });
    });
    // In this example an event listener is attached to the list:
    $("ul#menu").bind("touchstart", function(e) {
         if (e.target.nodeName. === "LI") {
             console.log(e.target.innerText);
         }
    });
});

Both examples have the same result, touching a list item will output its content to the console. However, in the second version the code is more efficient because there is only one bound event. Remember that when using this technique of event delegation, you want to bind the event listener as close to the collection of elements as possible. This is because the evens bubble up from the target to where you’ve bound the event listener. In other words, binding all you event listeners to the body element would be extremely inefficient because all events would have to bubble all the way up to the body tag before you could capture them. So, attach you event listeners where it makes sense.

Update Nov 19, 2010

As of version 1.0.7, ChocolateChip has two new methods for delegating events and triggering events:

Element.delegate()

The Element.delegate() method takes three arguments: selector, event, callback. It attaches an event listener on the element to track the supplied event on its descendant nodes described by selector. When the designated event occurs, it executes the callback on the target element. The method passes the target element to the callback as an argument so that you have its scope inside the callback. Here’s an example of how to use the delegate method. Notice that we can reference the item that was touched by using the term item (could use any term here, it’s just a reference to the target element):

$("ul").delegate("li", "touchstart", function(item) {
    item.css("background-color: yellow");
});
$("ul").delegate("li", "touchend", function(item) {
    item.css("background-color: white");
});

Note: Jan 16, 2011

As of ChocolateChip version 1.0.9 the delegate method now works with elements having child nodes. This means that if you want to listen for an event on a complex control that has many descendant elements, the event will bubble up to the control to capture it. In previous versions the child elements would be the event target preventing delegation from working except on simple constructions. So, say you were delegating touch events for a list and the list items had text and images. With the earlier version of Element.delegate, if the user where to touch the images or text, the list item would not be the target of the event and the delegation would fail. Now this has been resolved. Now you can delegate events without worrying about whether the targets are simple or complex elements.

Element.trigger()

The element.trigger() method allows you to trigger an event on another element when interacting with another element, for example clicking on one element triggers a click on another element. To accomplish this, you execute the trigger method on the target element with the event you wish to trigger. Here’s how:

$("#link").bind("click", function() {
    console.log("You just clicked this link!");
});
// By clicking on #importantButton, a click will be triggered on #link button:
$("#importantButton").bind("click", function() {
    // Trigger an event on another element:
    $("#link").trigger("click");
});

New in ChocolateChip 2.0

Element.on()

This is equivalent in function to the same method in jQuery and Zepto. It expects at least an event type and a callback.

$(function() {
   $('#clickButton').on('click', function() {
      console.log('You just clicked this button!');
      console.log(this.nodeName) // returns name of node.
   };
});

You can also use the same method to implement a delegate event listener. The following example implements a delegate on the body tag to listen for a click on any element with a class of ‘button’:

$(function() {
   $('body').on('click', '.button', function() {
      console.log('You just clicked this button!');
      console.log(this.nodeName) // returns name of node.
   };
});

Element.off()

This is the equivalent of unbind() and undelegate().

$(function() {
	// Normal event unbinding:
   $('#clickButton').off('click', 'buttonClickHandler');
   // Delegate unbinding:
   $('body').on('click', '.button', 'buttonClickHandler');
});

Traversing the DOM

Comments Off on Traversing the DOM

DOM level 3 is a high quality precision tool to work with

The biggest pain in Web development is DOM traversal. You think you’re getting an element node, but you wind up getting an empty text node instead. Or worse still, there’s a bunch of them in your collection and it throws your calculations off. That’s why people use libraries like Prototype, jQuery, Mootools, YUI, Dojo, or any of the others. DOM level 3 finally gives us an unambiguous way to get an element node. ChocolateChip takes advantage of these new traversal tools to make it even easier to get around the DOM. Here’s the breakdown on what we’ve got:

  1. Element.firstElementChild
  2. Element.lastElementChild
  3. Element.previousElementSibling
  4. Element.nextElementSibling
  5. Element.children
  6. Element.childElementCount
  7. Element.first()
  8. Element.last()
  9. Element.previous()
  10. Element.next()
  11. Element.ancestor() New in version 1.1.1
  12. Element.ancestorByTag()
  13. Element.ancestortByClass()
  14. Element.ancestortByPosition()
  15. Element.contains()
  16. Element.isEqualNode()
  17. Element.isSameNode()

As of version 1.3.0, the following methods are available:

  1. Element.is()
  2. Element.not()
  3. Element.isnt() [same as Element.not()]
  4. Element.has()
  5. Element.hasNot()
  6. Element.hasnt() [same as Element.hasNot()]
  7. Element.childElements()
  8. Element.kids()
  9. Element.closest()

Element.firstElementChild

firstElementChild is a new property introduced in DOM level 3. It indicates a first child node that is an element, never an empty text node.

$(function() {
    var article = $("article");
    var firstParagraph = article.firstElementChild;
    firstParagraph.addClass("highlight");     
});

Element.lastElementChild

lastElementChild is a new property introduced in DOM level 3. It indicates a last child node that is an element, never an empty text node.

$(function() {
    var article = $("article");
    var lastParagraph = article.lastElementChild;
    lastParagraph.addClass("highlight");     
});

previousElementSibling is a new property introduced in DOM level 3. It indicates the previous sibling node that is an element, never an empty text node.

Element.previousElementSibling

$(function() {
    var section = $("section:first-of-type");
    // Get the last paragraph:
    var lastPara = section.lastElementChild;
    // Get the paragraph before the last paragraph:
    lastPara.previousElementSibling.addClass("highlight");   	
});

Element.nextElementSibling

nextElementSibling is a new property introduced in DOM level 3. It indicates the next sibling node that is an element, never an empty text node.

    var section = $("section:first-of-type");
    // Get the first paragraph:
    var firstPara = section.firstElementChild;
    // Get the paragraph after the first paragraph:
    firstPara.nextElementSibling.addClass("highlight");   

Element.children

children indicates the children of an element that are actual elements, leaving out any empty text nodes. This is an HTML collection, so it has a length property and can be iterated over with a loop. In contrast, the childNodes property returns all child nodes, including empty text nodes.

var children = $("article").children;
for (var i = 0; children.length < i; i++) {
    children[i].css("background-color: orange; color: red;");
}

Element.childElementCount

DOM level 3 provides a new property for indicating the number of element child nodes minus empty text nodes. Of course, you could also just query the length property of what the children property returns.

var howManyKids = $("article > section:nth-of-type(3)").childElementCount;
$("#childCount").fill("The number of child nodes is: " + howManyKids);

Element.first()

Element.first() is a ChocolateChip convenience method for getting the first child of an element. It’s less letters to type than the methods mentioned earlier, but with the same result.

// Get the last section's first child and fill it with text.
$("section:last-of-type").first().fill("This is the first paragraph.");

Element.last()

Element.last() is a ChocolateChip convenience method for getting the last child of an element. It’s less letters to type than the methods mentioned earlier, but with the same result.

// Get the 8th section's last child and add the class "important"
$("section:nth-of-type(8)").last().addClass("important");

Element.previous()

Element.previous() is a ChocolateChip convenience method for getting the previous sibling of an element. It’s less letters to type than the methods mentioned earlier, but with the same result.

// Get the second paragraph of #MainSection:
var mainParag = $("#MainSection p:nth-of-type(2)");
// Remove the class "secondary".
mainParag.removeClass("secondary");
// Add the class "special" to the paragraph before mainParag:
mainParag.previous().addClass("special");

Element.next()

Element.next() is a ChocolateChip convenience method for getting the next sibling of an element. It’s less letters to type in the methods mentioned earlier, but with the same result.

var firstItem = $("li:first-of-type");
firstItem.addClass("first-item");
firstItem.next().addClass("secondary");

Update: Feb 14, 2011

As of version 1.1.1, ChocolateChip now has a new method for getting the ancestor of a tag: Element.ancestor. The other ancestor methods, Element.ancestorByClass, Element.ancestorByTag and Element.ancestorByPosition, are deprecated and are now aliases to Element.ancestor.

Element.ancestor()

This method accepts one argument which can be one of four types: a position (numeric value), a tag, a class (delimited with an initial “.”) or and id (delimited with an initial “#”). This method can be used to get the ancestor of an element with the matching selector or to verify that an element is the descendant of an element with the supplied selector. In the case of a tag or class, Element.ancestor will return the first instance of the tag or class climbing up from the starting point. Any tag passed as an argument must be plain, meaning, without any attributes. You can test for the presence of an attribute on a tag by using a condition check on the returned node (see examples below).

// Will return the third ancestor tag:
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("div");
// To find a tag with an attribute, use conditional checking:
var ancestorWithAttribute = $("#someID").ancestor("div");
if (ancestorWithAttribute.hasAttribute("rel") {
    console.log("This tag has a rel value of: " + ancestorWithAttribute.getAttribute("rel");
}

Element.ancestorByTag()

As of version 1.1.1, this tag is deprecated in favor of Element.ancestor() (see above)

Element.ancestortByTag() is a ChocolateChip method for getting the first instance of an ancestor of an element based on that ancestor’s tag.

$(".backButton").ancestorByTag("section").addClass("updated");

Element.ancestorByClass()

As of version 1.1.1, this tag is deprecated in favor of Element.ancestor() (see above)

Element.ancestorByClass() is a ChocolateChip method for getting the first instance of an ancestor of an element based on that ancestor’s class.

$(".nextButton").parentByClass("main").css("border: solid 2px red");

As of version 1.1.1, this tag is deprecated in favor of Element.ancestor() (see above)

Element.ancestorByPostion()

Element.ancestorByPostion() is a ChocolateChip method for getting the ancestor of an element at the designated position in the document. If no position is provided, it returns the immediate parent element. If the position provided is greater than the number of ancestor nodes for that element, it returns the body tag as the final ancestor.

<body>
    <article>
        <section>
            <header>
                <div class="button">
                              //....

$.ready(function() {
    console.log($(".button").ancestorByPosition().nodeName); // => HEADER
    console.log($(".button").ancestorByPosition(1).nodeName); // => HEADER
    console.log($(".button").ancestorByPosition(2).nodeName); // => SECTION
    console.log($(".button").ancestorByPosition(3).nodeName); // => ARTICLE
    console.log($(".button").ancestorByPosition(4).nodeName); // => BODY
    console.log($(".button").ancestorByPosition(20).nodeName); // => BODY
});

New methods since version 1.3.0:

Element.is()

This method returns the element if it matches the argument. The argument can be a tag, class or attribute.

Element.not()

This method returns the element if it does not match the argument. The argument can be a tag, class or attribute.

Element.has()

This method returns the element if one of its child nodes matches the argument. The argument can be a tag, class or attribute.

Element.hasNot()

This method returns the element if one of its child nodes does not match the argument. The argument can be a tag, class or attribute.

Element.childElements()

This method the child nodes of the element. If no argument is provided, it returns all of the element’s child nodes. If an argument is passed, it returns all child nodes that match the argument. Possible arguments are: tag, class or attribute.

Element.kids()

This is an alias for Element.childElements.

Element.closest()

This is an alias for Element.ancestor to match the function of the same name used by jQuery and Zepto.

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()

Element.text()

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:

<section>
	<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>
	<ul>
		<li>Butterflies</li>
		<li>Godzilla</li>
		<li>Care Bears</li>
		<li>Rattlesnakes</li>
		<li>Unicorns</li>
	</ul>
</section>
$(function() {
    // Will return "The first paragraph is always the best"
    console.log($("p:first-of-type).text());
    // 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"
    $("li:nth-of-type(4).text("Anacondas");
    console.log("The fourth list item was: " + listItem + ", but now it is: " + $("li:nth-of-type(4)").text());
});

Element.empty()

This method empties and element of all its child nodes.

$(function() {
    $("#response").empty();
});

Element.innerText

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.

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

$(function() {
    console.log($("table").innerText);
});

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.

Element.outerText

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.

Element.textContent

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

$(function() {
    console.log($("table").textContent);
});

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.

String.trim()

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

<ul>
		<li>item 1</li>
		<li>item 2</li>
		<li>item 3</li>
		<li>item 4</li>
		<li>     item 5     </li>
	</ul>
$(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:

$.concat()

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);
    str.prepend("#message");
}
outputString("This"," ","is"," ","a"," ","tedious"," ","example",".");

Older Entries