A Look Inside Zepto.js

2010-10-04 00:00:00 +0100 by Alex R. Young

Zepto.js is a small library for working with mobile WebKit browsers by Thomas Fuchs and released under
the MIT License. The library's API is similar to jQuery, allowing method
chaining, and familiar syntax for and element functions. Here are a few

// Return paragraph tags

// Change the HTML inside a paragraph
$('p').html('Hello World')

// Change the style too
$('p').html('Hello World').css('background-color: red')

// Iterate over each element
$('div').each(function(element) {
  // element is the actual node

// Animate an element using webkit-transform
$('div').anim('rotate(720deg)', 0.5, 10);

Zepto contains a lot of tricks to keep the library size down. Targeting
WebKit is one way it keeps a smaller size -- if you follow our framework
series you'll know how much work cross-browser support can be.

The first thing I noticed was a lot of void
rather than a comparison against undefined or typeof
variable === 'undefined'

The chained API is created by returning fn inside

function fn(_){ return fn.dom.forEach(_), fn }

Because \$() can accept many different types
(Array, String, Element), there's a complicated set of ternary operators to correctly set up the DOM
querying state. It looks confusing at first, but there's some neat code
in there. For example, to check if the function has already been run on
the argument, (typeof _ == 'function' && 'dom' in _) will
return true. Here the in

is used to detect a property. Just to illustrate:

'dom' in { 'dom': 'example', 'another': 'example 2' }
// true
'another' in { 'dom': 'example', 'another': 'example 2' }
// true
'example' in { 'dom': 'example', 'another': 'example 2' }
// false

Fuchs has been actively updating Zepto since he announced it. It's full
of interesting tricks to keep space down (like
Emile), but use what you learn from these libraries with caution -- they're specifically designed to be
small rather than easy for colleagues and collaborators to read!

Fuchs also released JS1k intro: fun with CSS transforms and hardware

today (madrobby / js1k-finals)
which is like a mini old school scene demo.