Download Zepto

The default build includes the following modules:
Core, Ajax, Event, Form, IE.

Zepto v1.0 bundles the Effects, iOS3, and Detect modules by default.
Please see below.Optional Modules。

Or grab the latest version on GitHub.

Use a script tag to include Zepto at the bottom of your page:

...
<script src=zepto.min.js></script>
</body>
</html>

if$Variable not yet defined, Zepto only sets the global variable$Points to itself. None.Zepto.noConflictmethod.

If you need to support older browsers, such as Internet Explorer 9 or below, you can fall back to jQuery 1.x.

Browser support

Primary (100% support)

Secondary targets (fully or mostly supported)

It should be noted that some of Zepto's optional features are specifically for mobile browsers; because its initial goal was to provide a streamlined jQuery-like JS library on mobile.

When developing page applications in browsers (Safari, Chrome, and Firefox) or building HTML-based web-view native applications, youPhoneGap, using Zepto is a good choice.

In short, Zepto is intended to be used as a base environment in all modern browsers. Zepto does not support older versions of Internet Explorer (<10).

Manually building Zepto

zepto.jsandzepto.min.jsProvide the above usage methods. However, for better program performance and flexibility, you can select modules and test when building Zepto.js and zepto.min.js from Zepto source code, usingUglifyJSGenerate code according to your needs (the most minimal code when gzip is enabled on the server).

About how to build Zeptothe README, including running tests and patches.

Zepto modules

module default description
zepto ✔ Core module; contains many methods
event ✔ Throughon()& off()Handle Events
ajax ✔ XMLHttpRequest and JSONP Practical Features
form ✔ Serialize & submit web forms
ie ✔ Added support for desktop Internet Explorer 10+ and Windows Phone 8.
detect Provide$.osand$.browserMessage
fx The animate()Methods
fx_methods in the form of animation.show, hide, toggle, andfade*()Method.
assets Experimental support for clearing iOS memory after removing image elements from the DOM.
data a comprehensivedata()Method, capable of storing arbitrary objects in memory.
deferred Provide$.Deferredpromises API. Depends on the "callbacks" module.
When including this module, $.ajax() Supports chained callbacks with the promise interface.
callbacks Provide for the "deferred" module$.Callbacks。
selector Experimental support.jQuery CSS expressionsPractical features, such as$('div:first')andel.is(':visible')。
touch Trigger tap– and swipe– related events on touch devices. This applies to all `touch` (iOS, Android) and `pointer` events (Windows Phone).
gesture Triggers pinch gesture events on touch devices.
stack ProvideandSelf& end()chained method calls.
ios3 String.prototype.trim and Array.prototype.reduce Methods (iftheyDoes not exist) , in order to兼容 iOS 3.x.

Creating plugins

Plugins can be written by adding methods as $.fn properties of

;(function($){
  $.extend($.fn, {
    foo: function(){
      // `this` refers to the current Zepto collection.
      // When possible, return the Zepto collection to allow chaining.
      return this.html('bar')
    }
  })
})(Zepto)

To better start developing plugins, first look atsource of Zepto's core module, and confirm that you have readcoding style guidelines


Core methods

$()

$(selector, [context])  ⇒ collection
$(<Zepto collection>)  ⇒ same collection
$(<DOM nodes>)  ⇒ collection
$(htmlString)  ⇒ collection
$(htmlString, attributes)  ⇒ collection v1.0+
Zepto(function($){ ... }) 

Create a Zepto collection object by executing a CSS selector, wrapping DOM nodes, or creating multiple elements from an HTML string.

A Zepto collection is an array-like object with chainable methods to manipulate the DOM nodes it points to. Except for $(ZeptoIn addition to direct methods on the object (such as$.extend), all methods in the document object are collection methods.

If a content parameter (CSS selector, DOM, or Zepto collection object) exists in the selector, then the CSS selector is only performed in the context of the given node; this feature is the same as using$(context).find(selector)is the same.

When given an HTML string fragment to create a DOM node. You can also create nodes by giving a set of attribute mappings. The fastest way to create a single element, use<div>or<div/>format.

When a function is attached toDOMContentLoadedIn the event handling flow. If the page has already finished loading, this method will be executed immediately.

$('div')  //=> 所有页面中得div元素
$('#foo') //=> ID 为 "foo" 的元素

// 创建元素:
$("<p>Hello</p>") //=> 新的p元素
// 创建带有属性的元素:
$("<p />", { text:"Hello", id:"greeting", css:{color:'darkblue'} })
//=> <p id=greeting style="color:darkblue">Hello</p>

// 当页面ready的时候,执行回调:
Zepto(function($){
  alert('Ready to Zepto!')
})

Not supportedjQuery CSS Extensions, however, the optional 'selector' module provides limited support for a few of the most commonly used pseudo-selectors, and can be discarded, for compatibility with existing code or plugin execution.

if$Variable not yet defined, Zepto only sets the global variable$Points to itself. Allows you to use Zepto along with useful legacy code, e.g., prototype.js. As long as Prototype is loaded first, Zepto will not overwrite Prototype's $ function. Zepto will always set the global variableZeptopoints to itself.

$.camelCase v1.0+

$.camelCase(string)  ⇒ string

Converts a string to a new string in camelCase. If the character is already in camelCase, it remains unchanged.

$.camelCase('hello-there') //=> "helloThere"
$.camelCase('helloThere')  //=> "helloThere"

$.contains v1.0+

$.contains(parent, node)  ⇒ boolean

Checks whether the parent node contains the given DOM node. If both are the same node, it returnsfalse。

$.each

$.each(collection, function(index, item){ ... })  ⇒ collection

Iterates over array elements or iterates over objects as key-value pairs. The callback function returnsfalsestop traversing when.

$.each(['a', 'b', 'c'], function(index, item){
  console.log('item %d is: %s', index, item)
})

var hash = { name: 'zepto.js', size: 'micro' }
$.each(hash, function(key, value){
  console.log('%s: %s', key, value)
})

$.extend

$.extend(target, [source, [source2, ...]])  ⇒ target
$.extend(true, target, [source, ...])  ⇒ target v1.0+

Extends the target object's properties with the source object's properties; the source object's properties will override the target object's properties.

By default, it is a shallow copy. If the first argument is true, it means a deep copy.

var target = { one: 'patridge' },
    source = { two: 'turtle doves' }

$.extend(target, source)
//=> { one: 'patridge',
//     two: 'turtle doves' }

$.fn

Zepto.fnIs an object that has all the methods available on Zepto objects, such asaddClass(), attr(), and other methods. Add a method to this object, and it will be available on all Zepto objects.

Here is an implementation of Zepto'sempty()Example of the method:

$.fn.empty = function(){
  return this.each(function(){ this.innerHTML = '' })
}

$.grep v1.0+

$.grep(items, function(item){ ... })  ⇒ array

Returns a new array containing only the items for which the callback function returns true.

$.grep([1,2,3],function(item){
    return item > 1
});//=>[2,3]
    

$.inArray v1.0+

$.inArray(element, array, [fromIndex])  ⇒ number

Returns the index of the specified element in the array (Yuren Dock note: 0-based), or returns-1。

Yuren Dock's note:[fromIndex]The parameter is optional, indicating from which index to search forward.

$.inArray("abc",["bcd","abc","edf","aaa"]);//=>1

$.inArray("abc",["bcd","abc","edf","aaa"],1);//=>1

$.inArray("abc",["bcd","abc","edf","aaa"],2);//=>-1
         

$.isArray

$.isArray(object)  ⇒ boolean

Return true if object is an array.

$.isFunction

$.isFunction(object)  ⇒ boolean

Return true if object is a function.

$.isPlainObject v1.0+

$.isPlainObject(object)  ⇒ boolean

Tests whether the object is a 'plain' object, created by object literal ("{}") ornew Objectcreated, if so, returns true.

$.isPlainObject({})         // => true
$.isPlainObject(new Object) // => true
$.isPlainObject(new Date)   // => false
$.isPlainObject(window)     // => false

$.isWindow v1.0+

$.isWindow(object)  ⇒ boolean

If the object parameter is a window object, returns true. This is very useful when dealing with iframes, because each iframe has its own window object, and using conventional methodsobj === windowto validate these objects will fail.

$.map

$.map(collection, function(item, index){ ... })  ⇒ collection

Iterate through the elements of the collection, returning all results of the iterator function (Yuren Dock note: a new array)nullandundefinedwill be filtered out.

$.map([1,2,3,4,5],function(item,index){
        if(item>1){return item*item;}
}); 
// =>[4, 9, 16, 25]

$.map({"yao":1,"tai":2,"yang":3},function(item,index){
    if(item>1){return item*item;}
}); 
// =>[4, 9]

$.parseJSON v1.0+

$.parseJSON(string)  ⇒ object

NativeJSON.parseAn alias for the method. (Yuren Dock note: accepts a standard JSON string and returns the parsed JavaScript object.)

$.trim v1.0+

$.trim(string)  ⇒ string

Remove whitespace from both ends of the string. Similar to String.prototype.trim().

$.type v1.0+

$.type(object)  ⇒ string

Gets the type of a JavaScript object. Possible types are:null undefined boolean number string function array date regexp object error。

For other objects, it simply reports 'object'. If you want to know whether an object is a plain JavaScript object, useisPlainObject。

add

add(selector, [context])  ⇒ self

Adds elements to the current set of matched elements. If a content parameter is given, it will only search within the content elements; otherwise, it searches the entire document.

<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
</ul>
<p>a paragraph</p>

<script type="text/javascript">
    $('li').add('p').css('background-color', 'red');
</script>

addClass

addClass(name)  ⇒ self
addClass(function(index, oldClassName){ ... })  ⇒ self

Adds the specified class name to each matched element. Multiple class names are separated by spaces.

after

after(content)  ⇒ self

Inserts content after each matched element (Yuren Dock note: external insertion). Content can be an HTML string, a DOM node, or an array of nodes.

$('form label').after('<p>A note below the label</p>')

append

append(content)  ⇒ self

Inserts content at the end of each matched element (Yuren Dock note: internal insertion). Content can be an HTML string, a DOM node, or an array of nodes.

$('ul').append('<li>new list item</li>')

appendTo

appendTo(target)  ⇒ self

Inserts matched elements at the end of the target element (Yuren Dock note: internal insertion). This is somewhat likeappend, but the insertion target is the opposite.

$('<li>new list item</li>').appendTo('ul')

attr

attr(name)  ⇒ string
attr(name, value)  ⇒ self
attr(name, function(index, oldValue){ ... })  ⇒ self
attr({ name: value, name2: value2, ... })  ⇒ self

Reads or sets DOM attributes. If no value parameter is given, reads the attribute value of the first element in the object collection. When a value parameter is given, sets the attribute value for all elements in the collection. When the value parameter isnull, then this attribute will be removed (similar toremoveAttr), multiple attributes can be set via an object key-value pair.

To read DOM attributes such ascheckedandselected, useprop。

var form = $('form')
form.attr('action')             //=> 读取值
form.attr('action', '/create')  //=> 设置值
form.attr('action', null)       //=> 移除属性

// 多个属性:
form.attr({
  action: '/create',
  method: 'post'
})

before

before(content)  ⇒ self

Inserts content before each matched element (Yuren Dock note: external insertion). Content can be an HTML string, a DOM node, or an array of nodes.

$('table').before('<p>See the following table:</p>')

children

children([selector])  ⇒ collection

Get the direct children of each element in the collection of matched elements. If a selector is given, the returned result only contains elements that match the CSS selector.

$('ol').children('*:nth-child(2n)')
//=> every other list item from every ordered list

clone v1.0+

clone()  ⇒ collection

Copy all elements in the collection through deep cloning.

This method does not copy data and event handlers to the new elements. This differs from jQuery, which uses a parameter to determine whether to copy data and event handlers.

closest

closest(selector, [context])  ⇒ collection
closest(collection)  ⇒ collection v1.0+
closest(element)  ⇒ collection v1.0+

Starting from the element itself, matches ancestor elements level by level, and returns the first element that matches the selector. If a context node parameter is given, only matches descendant elements of that node. This method isparents(selector)somewhat similar to, but it only returns the first matched ancestor element.

If the argument is a Zepto object collection or an element, the result must match the given element rather than a selector.

var input = $('input[type=text]')
input.closest('form')

concat

concat(nodes, [node2, ...])  ⇒ self

Adds elements to a Zepto object collection to form a new array. If the argument is an array, the elements in that array will be merged into the Zepto object collection.

This is a method provided by Zepto, not a jQuery API.

contents v1.0+

contents()  ⇒ collection

Gets the child elements of each matched element, including text and comment nodes. (Yuren Dock note: .contents() and.children()are similar, except the former includes text nodes as well as HTML elements generated in jQuery objects.)

css

css(property)  ⇒ value
css([property1, property2, ...])  ⇒ object v1.1+
css(property, value)  ⇒ self
css({ property: value, property2: value2, ... })  ⇒ self

Reads or sets CSS properties of DOM elements. When the value parameter is absent, returns the CSS property of the first element in the object collection. When the value parameter is present, sets the corresponding CSS property for each element in the collection.

Multiple properties can be fetched at once by passing an array of property names. Multiple properties can be set using an object key-value pair.

When value is empty (empty string,nullorundefined), that CSS property will be removed. When the value parameter is a unitless number, if the CSS property requires a unit, 'px' will be automatically added to the property.

var elem = $('h1')
elem.css('background-color')          // read property
elem.css('background-color', '#369')  // set property
elem.css('background-color', '')      // remove property

// set multiple properties:
elem.css({ backgroundColor: '#8EE', fontSize: 28 })

// read multiple properties:
elem.css(['backgroundColor', 'fontSize'])['fontSize']

data

data(name)  ⇒ value
data(name, value)  ⇒ self

Read or write the DOM'sdata-*attributes. The behavior is a bit likeattr, but attribute names are prefixed withdata-。

When reading attribute values, the following conversions will occur:v1.0+

  • "true", "false", and "null" are converted to the corresponding types;
  • Numeric values are converted to actual numeric types;
  • JSON values will be parsed if they are valid JSON;
  • everything else is returned as a string.

    Zepto's basic implementation of `data()` can only store strings. If you want to store arbitrary objects, include the optional 'data' module in your build of Zepto.

each

each(function(index, item){ ... })  ⇒ self

Iterates over each element in an object collection. In the iteration function,thisthe keyword points to the current item (passed as the second argument to the function). If the iteration function returnsfalse, traversal ends.

$('form input').each(function(index){
  console.log('input %d is: %o', index, this)
})

empty

empty()  ⇒ self

Clears the DOM content of each element in the object collection.

eq

eq(index)  ⇒ collection

Gets the element at the given index (Yuren Dock note: 0-based) from the current object collection.

$('li').eq(0)   //=> only the first list item
$('li').eq(-1)  //=> only the last list item

filter

filter(selector)  ⇒ collection
filter(function(index){ ... })  ⇒ collection v1.0+

Filters the object collection, returning items that match the CSS selector. If the argument is a function, an element is returned only when the function returns a truthy value. In the function,thisThe keyword points to the current element.

For the opposite functionality, seenot.

find

find(selector)  ⇒ collection
find(collection)  ⇒ collection v1.0+
find(element)  ⇒ collection v1.0+

Within the current object collection, finds the descendant elements of each element that match the CSS selector.

If a Zepto object collection or element is given, filters them; only those that are in the current Zepto collection object will be returned.

var form = $('#myform')
form.find('input, select')

first

first()  ⇒ collection

Gets the first element in the current object collection.

$('form').first()

forEach

forEach(function(item, index, array){ ... }, [context]) 

Iterates over each element in the object collection, somewhat similar to each, but the parameters of the traversal function are different, when the function returnsfalse, the traversal will not stop.

This is a method provided by Zepto, not a jQuery API.

get

get()  ⇒ array
get(index)  ⇒ DOM node

Get all elements or a single element from the current object collection. When the index parameter is absent, return all elements as a plain array. When index is specified, return only the element at that position. This is different fromeqin that this method returns DOM nodes, not a Zepto object collection.

var elements = $('h2')
elements.get()   //=> get all headings as an array
elements.get(0)  //=> get first heading node

has v1.0+

has(selector)  ⇒ collection
has(node)  ⇒ collection

Determine whether the child elements of the current object collection contain any element that matches the selector, or whether they contain the specified DOM node. If so, return a new object collection that filters out objects that do not contain an element matching the selector or do not contain the specified DOM node.

$('ol > li').has('a[href]')
//=> get only LI elements that contain links

hasClass

hasClass(name)  ⇒ boolean

Check whether any element in the object collection contains the specified class.

<ul>
    <li>list item 1</li>
    <li class="yaotaiyang">list item 2</li>
    <li>list item 3</li>
</ul>
<p>a paragraph</p>

<script type="text/javascript">
    $("li").hasClass("yaotaiyang");
  //=> true
</script>

height

height()  ⇒ number
height(value)  ⇒ self
height(function(index, oldHeight){ ... })  ⇒ self

Get the height of the first element in the object collection; or set the height of all elements in the object collection.

$('#foo').height()   // => 123
$(window).height()   // => 838 (viewport height)
$(document).height() // => 22302

hide

hide()  ⇒ self

Hide elements in this collection by setting their display CSS property to none.

By setting the CSS propertydisplayisnoneto hide the elements in the object collection.

html

html()  ⇒ string
html(content)  ⇒ self
html(function(index, oldHtml){ ... })  ⇒ self

Get or set the HTML content of elements in the object collection. When no content parameter is given, return the innerHtml of the first element in the object collection. When the content parameter is given, use it to replace the content of each element in the object collection. content can beappendall types described in .

// autolink everything that looks like a Twitter username
$('.comment p').html(function(idx, oldHtml){
  return oldHtml.replace(/(^|\W)@(\w{1,15})/g,
    '$1@<a href="http://twitter.com/$2">$2</a>')
})

index

index([element])  ⇒ number

Get the index of an element (Yuren Matou note: counting starts from 0). When the element parameter is not given, return the position of the current element among its siblings. When the element parameter is given, return its position in the current object collection. If the element is not found, return-1。

$('li:nth-child(2)').index()  //=> 1

indexOf

indexOf(element, [fromIndex])  ⇒ number

Get the position of an element in the current collection. If fromIndex number is given, search only from that position onwards. Returns the 0-based position when found and -1 if not found. Use of index is recommended over this method.

Get the index of an element in the current object collection (Yuren Matou note: counting starts from 0). If the fromIndex parameter is given, search from that position onward and return a 0-based index. If not found, return-1。indexThe method is implemented based on this method.

This is a Zepto method, not a jQuery API.

insertAfter

insertAfter(target)  ⇒ self

Insert the elements in the collection after the specified target element (Yuren Matou note: external insertion). This is somewhat like after, but used in the opposite way.

$('<p>Emphasis mine.</p>').insertAfter('blockquote')

insertBefore

insertBefore(target)  ⇒ self

Insert the elements in the collection before the specified target element (Yuren Matou note: external insertion). This is somewhat like before, but used in the opposite way.

$('<p>See the following table:</p>').insertBefore('table')

is

is(selector)  ⇒ boolean

Determine whether the first element in the current element collection matches a CSS selector. For non-standard selectors that jQuery basically supports, such as::visibleIncluded in the optional "selector" module.

jQuery CSS extensionsNot supported. Selecting the "selector" module can only support a limited number of the most commonly used forms.

last

last()  ⇒ collection

Get the last element in the object collection.

$('li').last()

map

map(function(index, item){ ... })  ⇒ collection

Traverse all elements in the object collection. Use the return value of the traversal function to form a new collection object. In the traversal function,thisthe keyword `this` points to the current item of the loop (the second parameter in the traversal function).

Return during traversalnullandundefined, the traversal will end.

// get text contents of all elements in collection
elements.map(function(){ return $(this).text() }).get().join(', ')

next

next()  ⇒ collection
next(selector)  ⇒ collection v1.0+

Get the next sibling–optionally filtered by selector–of each element in the collection.

Get the next sibling node of each element in the object collection (optionally with a filter selector).

$('dl dt').next()   //=> the DD elements

not

not(selector)  ⇒ collection
not(collection)  ⇒ collection
not(function(index){ ... })  ⇒ collection

Filter the current object collection to obtain a new object collection whose elements do not match the CSS selector. If another parameter is a Zepto object collection, then none of the elements in the returned new Zepto object are contained in that parameter object. If the parameter is a function, only include elements for which the function execution returns a value of false. The function'sthisThe keyword points to the current loop element.

For the opposite functionality, seefilter.

offset

offset()  ⇒ object
offset(coordinates)  ⇒ self v1.0+
offset(function(index, oldOffset){ ... })  ⇒ self v1.0+

Get the position of the current element relative to the document. Returns an object containing:top, left, widthandheight

When given one containingleftandtopWhen a properties object is given, use these values to position each element in the collection relative to the document.

offsetParent v1.0+

offsetParent()  ⇒ collection

Find the first positioned ancestor element, meaning its CSSpositionProperty value is 'relative', 'absolute' or 'fixed'

parent

parent([selector])  ⇒ collection

Get the direct parent element of each element in the object collection. If a CSS selector parameter is given, filter out the elements that match.

parents

parents([selector])  ⇒ collection

Get all ancestor elements of each element in the object collection. If a CSS selector parameter is given, filter out the elements that match.

If you want to get the direct parent element, useparentIf you only want to get the first element that matches the CSS selector, useclosest。

$('h1').parents()   //=> [<div#container>, <body>, <html>]

pluck

pluck(property)  ⇒ array

Get the attribute value of each element in the object collection. The return value isnullorundefinedworth filtering out.

$('body > *').pluck('nodeName') // => ["DIV", "SCRIPT"]

// implementation of Zepto's `next` method
$.fn.next = function(){
  return $(this.pluck('nextElementSibling'))
}

This is a Zepto method, not a jQuery API.

position v1.0+

position()  ⇒ object

Get the position of the first element in the object collection. Relative tooffsetParent. When an absolutely positioned element is near another element, this method is useful.

Returns an object with properties: top, left.

var pos = element.position()

// position a tooltip relative to the element
$('#tooltip').css({
  position: 'absolute',
  top: pos.top - 30,
  left: pos.left
})

prepend

prepend(content)  ⇒ self

Insert the parameter content before each matched element (Yuren Matou note: insertion inside the element). The inserted elements can be an HTML string fragment, a DOM node, or an array of nodes.

$('ul').prepend('<li>first list item</li>')

prependTo

prependTo(target)  ⇒ self

Insert all elements before the target (Yuren Matou note: insertion inside the element). This is somewhat likeprepend, but in the opposite way.

$('<li>first list item</li>').prependTo('ul')

prev

prev()  ⇒ collection
prev(selector)  ⇒ collection v1.0+

Get the previous sibling node of each element in the object collection, filtered by a selector.

prop v1.0+

prop(name)  ⇒ value
prop(name, value)  ⇒ self
prop(name, function(index, oldValue){ ... })  ⇒ self

Read or set the attribute value of a DOM element. When reading attribute values, it takes precedence overattr, because these attribute values change due to user interaction, such ascheckedandselected。

abbreviated or lowercase names, such asfor, class, readonlyand similar attributes, will be mapped to actual properties, such ashtmlFor, className, readOnly, etc.

push

push(element, [element2, ...])  ⇒ self

Add elements to the end of the current collection.

Add elements to the end of the current object collection.

This is a Zepto method, not a jQuery API.

ready

ready(function($){ ... })  ⇒ self

Add an event listener that fires when the page DOM has finished loading and the "DOMContentLoaded" event is triggered. It is recommended to use$()to replace this usage.

reduce

reduce(function(memo, item, index, array){ ... }, [initial])  ⇒ value

andArray.reducehas the same usage, traversing the current object collection. memo is the value returned by the function in the previous iteration. Traverse iteratively.

This is a Zepto method, not a jQuery API.

remove

remove()  ⇒ self

Remove the elements in the current collection from their parent nodes, effectively removing them from the DOM.

removeAttr

removeAttr(name)  ⇒ self

Remove the specified attribute from all elements in the current object collection.

removeClass

removeClass([name])  ⇒ self
removeClass(function(index, oldClassName){ ... })  ⇒ self

Remove the specified class from all elements in the current object collection. If the name parameter is not specified, remove all classes. Multiple class name parameters can be separated by spaces. The following example removes two classes.

<input class="taiyang yueliang" id="check1" type="checkbox" checked="checked">
<input class="yaotaiyang" id="check2" type="checkbox"> <script type="text/javascript"> $("#check1").removeClass("taiyang yueliang") //=>[<input class id="check1" type="checkbox" checked="checked">] </script>

replaceWith

replaceWith(content)  ⇒ self

Replace all matched elements with the given content (including the elements themselves). The content parameter can bebeforethe type described in.

scrollLeft v1.1+

scrollLeft()  ⇒ number
scrollLeft(value)  ⇒ self

Get or set the number of pixels that the scrolling element on the page or the entire window scrolls to the right.

scrollTop v1.0+

scrollTop()  ⇒ number
scrollTop(value)  ⇒ self v1.1+

Get or set the number of pixels that the scrolling element on the page or the entire window scrolls downward.

show

show()  ⇒ self

Restore the default "display" value of each element in the object collection. If you usehidehide the element, this property can be used to show it. It is equivalent to removing thedisplay:none。

siblings

siblings([selector])  ⇒ collection

Get the sibling nodes of all elements in the object collection. If a CSS selector parameter is given, filter out the elements that match the selector.

size

size()  ⇒ number

Get the number of elements in the object collection.

slice

slice(start, [end])  ⇒ array

extract this arrayarraysubset of, fromstartstart, if givenend, extract fromstartStart toendending element, but not includingendthe element at position.

text

text()  ⇒ string
text(content)  ⇒ self
text(function(index, oldText){ ... })  ⇒ self v1.1.4+

Get or set the text content of elements in all object collections. When no content parameter is given, return the text content of the first element in the current object collection (including text content in child nodes). When the content parameter is given, use it to replace the text content of all elements in the object collection. It is somewhat similar tohtml, unlike it, it cannot be used to get or set HTML.

toggle

toggle([setting])  ⇒ self

Show or hide matched elements. Ifsettingis true, equivalent toshowmethod. Ifsettingis false. Equivalent tohidemethod.

var input = $('input[type=text]')
$('#too_long').toggle(input.val().length > 140)

toggleClass

toggleClass(names, [setting])  ⇒ self
toggleClass(function(index, oldClassNames){ ... }, [setting])  ⇒ self

Add or remove one or more style classes on each element in the matched element collection. If the class name exists, remove it; if it does not exist, add it. Ifsettingis truthy, this functionality is similar toaddClass, if false, this functionality is similar toremoveClass。

unwrap

unwrap()  ⇒ self

Remove the direct parent node of each element in the collection and keep their child elements in their original positions. Basically, this method removes the immediate ancestor element while keeping the current elements in the DOM.

$(document.body).append('<div id=wrapper><p>Content</p></div>')
$('#wrapper p').unwrap().parents()  //=> [<body>, <html>]

val

val()  ⇒ string
val(value)  ⇒ self
val(function(index, oldValue){ ... })  ⇒ self

Get or set the value of matched elements. When no value parameter is given, return the value of the first element. If it is a<select multiple>tag, return an array. When the value parameter is given, set the value of all elements.

width

width()  ⇒ number
width(value)  ⇒ self
width(function(index, oldWidth){ ... })  ⇒ self

Get the width of the first element in the object collection; or set the width of all elements in the object collection.

$('#foo').width()   // => 123
$(window).width()   // => 768 (viewport width)
$(document).width() // => 768 

wrap

wrap(structure)  ⇒ self
wrap(function(index){ ... })  ⇒ self v1.0+

Wrap an HTML element around each matched element. The structure parameter can be a single element or several nested elements. It can also be an HTML string fragment or a DOM node. It can also be a callback function used to generate the wrapper, and this function returns the wrapper fragment of the first two types.

It should be noted that:This method has very good support for nodes in the DOM. If youwrap()If used on a new element and then the result is inserted into the document, this method has no effect.

// wrap each button in a separate span:
$('.buttons a').wrap('<span>')

// wrap each code block in a div and pre:
$('code').wrap('<div class=highlight><pre /></div>')

// wrap all form inputs in a span with classname
// corresponding to input type:
$('input').wrap(function(index){
  return '<span class=' + this.type + 'field />'
})
//=> <span class=textfield><input type=text /></span>,
//   <span class=searchfield><input type=search /></span>

// WARNING: will not work as expected!
$('<em>broken</em>').wrap('<li>').appendTo(document.body)
// do this instead:
$('<em>better</em>').appendTo(document.body).wrap('<li>')

wrapAll

wrapAll(structure)  ⇒ self

Wrap a single structure around all matched elements. The structure can be a single element or several nested elements, and can be provided as an HTML string or a DOM node.

// wrap all buttons in a single div:
$('a.button').wrapAll('<div id=buttons />')

wrapInner

wrapInner(structure)  ⇒ self
wrapInner(function(index){ ... })  ⇒ self v1.0+

the ... in each elementcontentWrap in a single structure. The structure can be a single element or multiple nested elements, and can be provided as an HTML string or a DOM node, or as a callback function that generates the wrapper, which returns the wrapper fragment of the first two types.

// wrap the contents of each navigation link in a span:
$('nav a').wrapInner('<span>')

// wrap the contents of each list item in a paragraph and emphasis:
$('ol li').wrapInner('<p><em /></p>')

Detect methods

Detect module

This detection method allows you to fine-tune your site or application in different environments, and helps you identify phones and tablets; as well as different browsers and operating systems.

// The following boolean flags are set to true if they apply,
// if not they're either set to `false` or `undefined`.
// We recommend accessing them with `!!` prefixed to coerce to a boolean. 

// general device type
$.os.phone
$.os.tablet

// specific OS
$.os.ios
$.os.android
$.os.webos
$.os.blackberry
$.os.bb10
$.os.rimtabletos

// specific device type
$.os.iphone
$.os.ipad
$.os.ipod // [v1.1]
$.os.touchpad
$.os.kindle

// specific browser
$.browser.chrome
$.browser.firefox
$.browser.safari // [v1.1]
$.browser.webview // (iOS) [v1.1]
$.browser.silk
$.browser.playbook
$.browser.ie // [v1.1]

// 此外,版本信息是可用的。
// 下面是运行​​iOS 6.1的iPhone所返回的。
!!$.os.phone         // => true
!!$.os.iphone        // => true
!!$.os.ios           // => true
$.os.version       // => "6.1"
$.browser.version  // => "536.26"

Event handling

$.Event

$.Event(type, [properties])  ⇒ event

Create and initialize a specified DOM event. If a properties object is given, use it to extend the new event object. By default, the event is set to bubble mode; this can be changed by settingbubblesisfalseto close.

A function initialized by an event can usetriggerto trigger.

$.Event('mylib:change', { bubbles: false })

$.proxy v1.0+

$.proxy(fn, context)  ⇒ function
$.proxy(fn, context, [additionalArguments...])  ⇒ function v1.1.4+
$.proxy(context, property)  ⇒ function
$.proxy(context, property, [additionalArguments...])  ⇒ function v1.1.4+

Accept a function and return a new function, and this new function always maintains a specific context. In the new function,thispoints to the context parameter. In another form, the original function is read from a specific property of the context object.

If more than two extra arguments are passed, they are used as arguments for the function passed to the `fn` parameter.

var obj = {name: 'Zepto'},
    handler = function(){ console.log("hello from + ", this.name) }

// ensures that the handler will be executed in the context of `obj`:
$(document).on('click', $.proxy(handler, obj))

bind 🐶🔫

Deprecated, useonReplace.

bind(type, function(e){ ... })  ⇒ self
bind(type, [data], function(e){ ... })  ⇒ self v1.1+
bind({ type: handler, type2: handler2, ... })  ⇒ self
bind({ type: handler, type2: handler2, ... }, [data])  ⇒ self v1.1+

to bind an event handler to an element.

delegate 🐶🔫

Deprecated, useonReplace.

delegate(selector, type, function(e){ ... })  ⇒ self
delegate(selector, { type: handler, type2: handler2, ... })  ⇒ self

Attach an event handler to all elements matching the selector, based on a set of specific root elements. The matching elements may be created now or in the future.

die 🐶🔫

Deprecated, useonReplace.

die(type, function(e){ ... })  ⇒ self
die({ type: handler, type2: handler2, ... })  ⇒ self

Delete vialivethe added event.

event.isDefaultPrevented v1.1+

event.isDefaultPrevented()  ⇒ boolean

ifpreventDefault()Called by an instance of the event, returns true. This can serve as a cross-platform alternative to the native defaultPreventedproperty, if defaultPreventedWhen missing or unreliable in some browsers.

// trigger a custom event and check whether it was cancelled
var event = $.Event('custom')
element.trigger(event)
event.isDefaultPrevented()

event.isImmediatePropagationStopped v1.1+

event.isImmediatePropagationStopped()  ⇒ boolean

ifstopImmediatePropagation()Called by an instance of the event, returns true. Zepto implements it in browsers that do not support the native method, (such as old Android versions).

event.isPropagationStopped v1.1+

event.isPropagationStopped()  ⇒ boolean

ifstopPropagation()Called by an instance of the event, returns true.

live 🐶🔫

Deprecated, useonReplace.

live(type, function(e){ ... })  ⇒ self
live({ type: handler, type2: handler2, ... })  ⇒ self

Similardelegate, add an event handler to all elements matching the current selector. The matching elements may be created now or in the future.

off

off(type, [selector], function(e){ ... })  ⇒ self
off({ type: handler, type2: handler2, ... }, [selector])  ⇒ self
off(type, [selector])  ⇒ self
off()  ⇒ self

Remove viaonAdded event. Remove a specific event handler,on()the same function that was used to add it. Otherwise, calling this method with only the event type will remove all handlers of that type. If no arguments are given, it will remove all event handlers on the current element.Allof the registered event.

on

on(type, [selector], function(e){ ... })  ⇒ self
on(type, [selector], [data], function(e){ ... })  ⇒ self v1.1+
on({ type: handler, type2: handler2, ... }, [selector])  ⇒ self
on({ type: handler, type2: handler2, ... }, [selector], [data])  ⇒ self v1.1+

Add event handlers to the elements in the object collection. Multiple events can be added as a space-separated string, or as an object with event types as keys and functions as values. If a CSS selector is given, the event is only triggered when it fires on an element matching that selector (Yuren Dock's note: i.e., event delegation, or event proxy).

If givendataparameter; this value will be used as `this` during the execution of the event handler. event.data Property

The event handler is executed in the context of the element to which the handler is added, or, if a selector is given, the element matching that selector (Yuren Dock's note: `this` points to the element that triggered the event).false,preventDefault()andstopPropagation()when invoked by the current event, it will prevent the default browser action, such as following a link.

iffalsePassed to this method as an argument in place of a callback function, it is equivalent to passing a function that directly returnsfalse. (Yuren Dock note: i.e.falseTreat asfunction(e){ ... }the parameter, asfunction(){ return false; }the shorthand form of, for example:$("a.disabled").on("click", false);This is equivalent to$("a.disabled").on("click", function(){ return false; } );)

var elem = $('#content')
// observe all clicks inside #content:
elem.on('click', function(e){ ... })
// observe clicks inside navigation links in #content
elem.on('click', 'nav a', function(e){ ... })
// all clicks inside links in the document
$(document).on('click', 'a', function(e){ ... })
// disable following any navigation link on the page
$(document).on('click', 'nav a', false)

one

one(type, [selector], function(e){ ... })  ⇒ self
one(type, [selector], [data], function(e){ ... })  ⇒ self v1.1+
one({ type: handler, type2: handler2, ... }, [selector])  ⇒ self
one({ type: handler, type2: handler2, ... }, [selector], [data])  ⇒ self v1.1+

Add an event handler to an element. After the event is first executed, the handler will be automatically unbound, ensuring that the handler executes at most once on each element.selectoranddataFor parameter descriptions, see.on()。

trigger

trigger(event, [args])  ⇒ self

Trigger the specified event on the elements in the object collection. The event can be a string type, or an event object defined via$.Eventan event object. If the `args` argument is given, it is passed as arguments to the event function.

// add a handler for a custom event
$(document).on('mylib:change', function(e, from, to){
  console.log('change on %o with data %s, %s', e.target, from, to)
})
// trigger the custom event
$(document.body).trigger('mylib:change', ['one', 'two'])

Zepto only supports triggering events on DOM elements.

triggerHandler

triggerHandler(event, [args])  ⇒ self

liketrigger, it only triggers the event on the current element, but it does not bubble.


        $("input").triggerHandler('focus');
        // 此时input上的focus事件触发,但是input不会获取焦点
        $("input").trigger('focus');
        // 此时input上的focus事件触发,input获取焦点

unbind 🐶🔫

Deprecated, use off instead.

unbind(type, function(e){ ... })  ⇒ self
unbind({ type: handler, type2: handler2, ... })  ⇒ self

Remove viabindthe registered event.

undelegate 🐶🔫

Deprecated, use off instead.

undelegate(selector, type, function(e){ ... })  ⇒ self
undelegate(selector, { type: handler, type2: handler2, ... })  ⇒ self

Remove viadelegatethe registered event.


Ajax requests

$.ajax

$.ajax(options)  ⇒ XMLHttpRequest

Execute an Ajax request. It can be a local resource, or via a browser supportingHTTP access controlbrowsers, or viaJSONPto implement cross-domain.

Options:

  • type(Default: "GET"): request method ("GET", "POST", or other)
  • url(default: current address): the address to which the request is sent.
  • data(default: none): data sent to the server. If it is a GET request, it is automatically appended to the URL as parameters. Non-String objects will be serialized via$.paramget a serialized string.
  • processData(default: true): For non-GET requests, whether to automaticallydataConvert to a string.
  • contentType(default: "application/x-www-form-urlencoded"): the content encoding type when sending information to the server. (This can also be set viaheaders). By settingfalseskip setting default values.
  • mimeType(default: none): override the MIME type of the response.v1.1+
  • dataType(default: none): The data type expected from the server ("json", "jsonp", "xml", "html", or "text")
  • jsonp(default: "callback"): the name of the JSONP callback query parameter.
  • jsonpCallback(default: "jsonp{N}"): the name of the global JSONP callback function as a string (or a function returning one). Setting this option can enable browser caching.v1.1+
  • timeout(Default:0): request timeout in milliseconds,0means no timeout.
  • headers: an object of additional HTTP headers for the Ajax request.
  • async(default: true): By default, all requests are asynchronous. If you need to send a synchronous request, set this tofalse。
  • global(default: true): the request will trigger global Ajax event handlers; setting it to false will not trigger global Ajax events.
  • context(default: window): This object is used to set the context (this pointing) for Ajax-related callback functions.
  • traditional(default: false): activate the traditional way via$.paramto obtain the serializeddata。
  • cache(default: true): whether the browser should be allowed to cache GET responses. Fromv1.1.4on, when the `dataType` option is "script"orjsonpwhen, defaults tofalse。
  • xhrFields(default: none): An object whose properties are copied verbatim to an XMLHttpRequest instance.v1.1+
  • username & password(default: none): HTTP basic authentication credentials.v1.1+

If the URL contains=?ordataTypeis "jsonp", this request will be executed by injecting a<script>tag instead of using XMLHttpRequest (seeJSONP). At this pointcontentType, dataType, headershas restrictions,asyncnot supported.

Ajax callback functions

You can specify the following callback functions, which will be executed in the given order:

  1. beforeSend(xhr, settings): called before the request is sent; it receives the xhr object and settings as parameters. If it returnsfalse, the request will be canceled.

  2. success(data, status, xhr): called after the request succeeds. It is passed the returned data and a string containing the success code.

  3. error(xhr, errorType, error): called when the request fails. (Timeout, parse error, or status code not in HTTP 2xx).

  4. complete(xhr, status): called when the request completes, regardless of whether the request failed or succeeded.

Promise callback interfacev1.1+

If the optional "callbacks" and "deferred" modules are loaded, from$.ajax()The returned XHR object implements the promise interface for chained callbacks:

xhr.done(function(data, status, xhr){ ... })
xhr.fail(function(xhr, errorType, error){ ... })
xhr.always(function(){ ... })
xhr.then(function(){ ... })

These methods replacedsuccess, error, andcompletecallback option.

Ajax events

Whenglobal: truewhen. During the Ajax request lifecycle, the following events will be triggered.

  1. ajaxStart (global): triggered if no other Ajax requests are currently active.

  2. ajaxBeforeSend(data: xhr, options): Can be canceled before sending the request.

  3. ajaxSend(data: xhr, options): likeajaxBeforeSend, but cannot be canceled.

  4. ajaxSuccess(data: xhr, options, data): when the return is successful.

  5. ajaxError(data: xhr, options, error): when there is an error.

  6. ajaxComplete(data: xhr, options): after the request has completed, whether it succeeded or failed.

  7. ajaxStop (global): triggered if this is the last active Ajax request.

By default, Ajax events are triggered on the document object. However, if the request'scontextis a DOM node, the event will be triggered on this node and then bubble in the DOM. The only exception isajaxStart & ajaxStopthese two global events.

$(document).on('ajaxBeforeSend', function(e, xhr, options){
  // This gets fired for every Ajax request performed on the page.
  // The xhr object and $.ajax() options are available for editing.
  // Return false to cancel this request.
})

$.ajax({
  type: 'GET',
  url: '/projects',
  // data to be added to query string:
  data: { name: 'Zepto.js' },
  // type of data we are expecting in return:
  dataType: 'json',
  timeout: 300,
  context: $('body'),
  success: function(data){
    // Supposing this JSON payload was received:
    //   {"project": {"id": 42, "html": "<div>..." }}
    // append the HTML to context object.
    this.append(data.project.html)
  },
  error: function(xhr, type){
    alert('Ajax error!')
  }
})

// post a JSON payload:
$.ajax({
  type: 'POST',
  url: '/projects',
  // post payload:
  data: JSON.stringify({ name: 'Zepto.js' }),
  contentType: 'application/json'
})

$.ajaxJSONP 🐶🔫

Deprecated, use$.ajaxReplace.

$.ajaxJSONP(options)  ⇒ mock XMLHttpRequest

Execute JSONP to fetch data across domains.

This method is relatively$.ajaxThere is no advantage; it is recommended not to use it.

$.ajaxSettings

an object containing default settings for Ajax requests. Most of the settings have been described in$.ajaxthe preceding text. The following settings are particularly useful globally:

  • timeout(Default:0): set a non-zero value for Ajax requests to specify a default timeout, in milliseconds.
  • global(default: true): set to false to prevent triggering Ajax events.
  • xhr(default: XMLHttpRequest factory): Set to a function that returns an XMLHttpRequest instance (or a compatible object)
  • accepts: the MIME type requested from the server, specifyingdataTypeValue:
    • script: “text/javascript, application/javascript”
    • json: “application/json”
    • xml: “application/xml, text/xml”
    • html: “text/html”
    • text: “text/plain”

$.get

$.get(url, function(data, status, xhr){ ... })  ⇒ XMLHttpRequest
$.get(url, [data], [function(data, status, xhr){ ... }], [dataType])  ⇒ XMLHttpRequest v1.0+

Execute an Ajax GET request. This is a$.ajaxshorthand for.

$.get('/whatevs.html', function(response){
  $(document.body).append(response)
})

$.getJSON

$.getJSON(url, function(data, status, xhr){ ... })  ⇒ XMLHttpRequest
$.getJSON(url, [data], function(data, status, xhr){ ... })  ⇒ XMLHttpRequest v1.0+

Get JSON data via an Ajax GET request. This is a$.ajaxshorthand for.

$.getJSON('/awesome.json', function(data){
  console.log(data)
})

// fetch data from another domain with JSONP
$.getJSON('//example.com/awesome.json?callback=?', function(remoteData){
  console.log(remoteData)
})

$.param

$.param(object, [shallow])  ⇒ string
$.param(array)  ⇒ string

Serialize an object into a URL-encoded query string representation for data submitted in Ajax requests. If `shallow` is set to true, nested objects will not be serialized, and values of nested arrays will not use square brackets in their keys.

If the value of any property of an object is a function rather than a string, the function will be called and its return value will be serialized.

In addition, also acceptsserializeArrayan array in the format, where each item has "name" and "value" properties.

$.param({ foo: { one: 1, two: 2 }})
//=> "foo[one]=1&foo[two]=2)"

$.param({ ids: [1,2,3] })
//=> "ids[]=1&ids[]=2&ids[]=3"

$.param({ ids: [1,2,3] }, true)
//=> "ids=1&ids=2&ids=3"

$.param({ foo: 'bar', nested: { will: 'not be ignored' }})
//=> "foo=bar&nested[will]=not+be+ignored"

$.param({ foo: 'bar', nested: { will: 'be ignored' }}, true)
//=> "foo=bar&nested=[object+Object]"

$.param({ id: function(){ return 1 + 2 } })
//=> "id=3"

$.post

$.post(url, [data], function(data, status, xhr){ ... }, [dataType])  ⇒ XMLHttpRequest

Execute an Ajax POST request. This is a$.ajaxshorthand for.

$.post('/create', { sample: 'payload' }, function(response){
  // process response
})

dataThe argument can be a string:

$.post('/create', $('#some_form').serialize(), function(response){
  // ...
})

load

load(url, function(data, status, xhr){ ... })  ⇒ self

Load remote HTML content via GET Ajax and insert it into the current collection. In addition, a CSS selector can be specified in the URL, like so, so that the HTML content matching the selector can be used to update the collection.

$('#some_element').load('/foo.html #bar')

If no CSS selector is given, the full returned text is used.

Note that any JavaScript blocks will be executed when there is no selector. If a selector is included, script elements within the matched selector will be removed.


Form methods

serialize

serialize()  ⇒ string

Compile the values of form elements used for submission in an Ajax POST request into a URL-encoded string.

serializeArray

serializeArray()  ⇒ array

Compile the values of form elements used for submission into an array withnameandvalueAn array of objects. Form elements that cannot be used, buttons, unchecked radio buttons/checkboxes will be skipped. The result does not include data from file inputs.

$('form').serializeArray()
//=> [{ name: 'size', value: 'micro' },
//    { name: 'name', value: 'Zepto' }]

submit

submit()  ⇒ self
submit(function(e){ ... })  ⇒ self

Bind a handler function to the "submit" event, or trigger the "submit" event on an element. When no function parameter is given, trigger the "submit" event on the current form and execute the default form submission behavior, unless `preventDefault()` is called.preventDefault()。

When a function parameter is given, it simply binds a handler function to the "submit" event on the current element.


Effects

$.fx

Global animation settings:

  • $.fx.off(defaults to false in browsers that support CSS transitions): set to true to disable allanimate() transitions。

  • $.fx.speeds: an object used to set the animation duration.

    • _default (400 ms)
    • fast (200 ms)
    • slow (600 ms)

change an existing value or add a new property to affect animations that use a string for timing.

animate

animate(properties, [duration, [easing, [function(){ ... }]]])  ⇒ self
      animate(properties, { duration: msec, easing: type, complete: fn })  ⇒ self
      animate(animationName, { ... })  ⇒ self
  

Perform smooth CSS transition property changes on the elements in the current object collection.

  • properties: an object that contains the values of the CSS animation, or the name of the CSS keyframe animation.
  • duration(default 400): time in milliseconds, or a string.
    • fast (200 ms)
    • slow (600 ms)
    • any$.fx.speedsCustom attributes
  • easing(defaultlinear): specify the easing type of the animation, using one of the following:
  • complete: callback function when the animation completes.
  • li>delay: Transition delay time in millisecondsv1.1+

Zepto also supports the followingCSS transformAttributes:

  • translate(X|Y|Z|3d)
  • rotate(X|Y|Z|3d)
  • scale(X|Y|Z)
  • matrix(3d)
  • perspective
  • skew(X|Y)

If the duration parameter is0or$.fx.offis true (defaults to true in browsers that do not support CSS transitions), the animation will not be executed; instead, the target position of the animation effect will take effect immediately. Similarly, if the specified animation is not completed through animation, the animation target position will take effect immediately. In this case, there is no animation,completethe method will also not be called.

If the first argument is a string rather than an object, it will be treated as a CSS keyframe animationCSS keyframe animationthe name.

$("#some_element").animate({
        opacity: 0.25,
        left:
        '50px',
        color:
        '#ABCDEF',
        rotateZ:
        '45deg',
        translate3d: '0,10px,0'
        }, 500,
        'ease-out')
    

Zepto only uses CSS transition effects for animations. jQuery easings are not supported. jQuery's relative change ("=+10px") syntax is also not supported. Please refer tolist of animatable properties. Browser support may vary, so be sure to test the browsers you want to support.


Touch

Touch events

The “touch” module adds the following events, which can be usedonandoff。

  • tap— triggered when an element is tapped.
  • singleTap and doubleTap— This pair of events can be used to detect single tap and double tap on an element. (If you don't need to detect single tap or double tap, usetapinstead).
  • longTap— Triggered when an element is held down for more than 750ms.
  • swipe, swipeLeft, swipeRight, swipeUp, swipeDown— Triggered when an element is swiped. (Optionally with a given direction)

These events are also shortcut methods on all Zepto object collections.

<style>.delete { display: none; }</style>

<ul id=items>
  <li>List item 1 <span class=delete>DELETE</span></li>
  <li>List item 2 <span class=delete>DELETE</span></li>
</ul>

<script>
// show delete buttons on swipe
$('#items li').swipe(function(){
  $('.delete').hide()
  $('.delete', this).show()
})

// delete row on tapping delete button
$('.delete').tap(function(){
  $(this).parent('li').remove()
})
</script>

Change Log

v1.1.0 — 05 Dec 2013 — diff

Notable changes

  • IE10+ support
  • Huge speed optimizations for simple CSS selectors (classname, ID) and DOM element creation
  • Provide $.Callbacks and $.Deferred in optional modules
  • Removed fx and detect modules from default build

Ajax

  • New supported $.ajax() options:
    • xhrFields
    • mimeType
    • jsonpCallback
    • username & password
  • Promise interface supported when loading the optional “callbacks” and “deferred” modules:
    • xhr.done(function(data, status, xhr){ ... })
    • xhr.fail(function(xhr, errorType, error){ ... })
    • xhr.always(function(){ ... })
  • Enable mutating Ajax settings in the beforeSend callback
  • Fix JSONP callbacks for errored responses on Android
  • Ensure consistent Accept request HTTP header across browsers
  • Fix $.param() for jQuery compatibility when handling complex nested objects
  • Support IIS JavaScript MIME type
  • Pass “abort” and “timeout” status to global ajaxError event handlers

Event

  • Provide isDefaultPrevented(), stopImmediatePropagation(), and related methods for all events
  • Support the data argument in .bind(), .on(), and .one()
  • Support CSS selector argument in .one() for event delegation
  • Support .on('ready') as an alias for .ready()
  • Enable event handlers on plain old JS objects
  • Many fixes related to event delegation

Data

  • Cleanup .data() values on DOM element removal with .remove/empty()
  • .data() now assumes that numbers that begin with zeroes are strings
  • .removeData() (no argument) now removes all data on the element
  • Enable reading data-* attributes that have underscores in the name

Misc.

  • Support simple DOM property names in .prop(name) such as for, class, readonly…
  • Implement the .scrollLeft([value]) method
  • Support setting .scrollTop(value)
  • Fix $(document).width/height()
  • Support fetching multiple CSS values via array in .css(['prop1', 'prop2', ...])
  • Support setting CSS transition delay via delay option for .animate()
  • Ensure that .animate() callback always firesParty like it’s one-oh!_

v1.0 — 02 Mar 2013 — diff

Party like it’s one-oh!

Notable changes

  • Zepto is now compatible with Twitter Bootstrap
  • Portable, completely new node.js-based build system
  • Fully automated tests with PhantomJS and Travis CI
  • Removed touch module from default distribution

New features

  • $.fn.filter(function(index){ ... })
  • $.fn.contents()
  • $.fn.wrapInner()
  • $.fn.scrollTop()
  • $.contains()
  • $.fn.has()
  • $.fn.position()
  • $.fn.offsetParent()
  • $.parseJSON()
  • $.camelCase()
  • $.isWindow()
  • $.grep() (interface to Array.filter)
  • Support $(html, attributes) syntax for element creation
  • Emulate mouseenter and mouseleave events
  • Bootstrap compat: support $.fn.offset(coordinates)
  • Bootstrap compat: implement $.fn.detach()
  • Add support for Ajax cache: false option
  • Prevent scrolling when horizontal swipe events are detected
  • cancelTouch for tap events
  • prev and next now support an optional selector argument
  • $.fn.find and $.fn.closest now support Zepto objects as arguments
  • Enable deep copy via $.extend(true, target, source)
  • Enable nested structures for $.fn.wrap() and $.fn.wrapAll()
  • Enable function arguments for $.fn.wrap() and $.fn.wrapInner()
  • Support number, boolean, JSON types in data attributes
  • Support manipulating classnames on SVG elements
  • Enable named durations for animate, e.g. slow.
  • Support timing-function for animate
  • Support event properties passed to $.fn.trigger() or $.Event()
  • Selector module: support child > * queries
  • Add detect support for mobile Chrome browser
  • Add $.os.phone and $.os.tablet (booleans)
  • Detect Firefox mobile, Playbooks and BB10

Fixes

  • Fix passing null selector to on or off
  • Fixed bug where self-closing html tags would act as open tags
  • Fix val for multiple select
  • Fix various touch and gesture bugs.
  • Corrected parameters of load success callback to match jQuery.
  • Fix css with 0 values and falsy values
  • Fix a css performance issues with string values
  • Fix $.ajaxJSONP when invoked directly
  • Fix animate with 0 durations.
  • Fix toggle and fadeToggle for multiple elements.
  • Fix ajax $.fn.load behavior with selector
  • Make attr(name, null) unset attribute
  • Fix animate in Firefox
  • Fix animate for elements just added to DOM
  • Fix an escaping issue with $.param
  • Respect traditional: true option in $.ajax
  • Fix focus & blur event delegation and enable unbind
  • Simple wrapping for any object passed to $()
  • Enable children method for XML documents
  • Don’t eval <script> content when src is present
  • Support processData option for $.ajax()
  • Enable passing contentType: false to $.ajax()
  • Apply focus() and blur() to all elements in collection
  • Change $.fn.map() to return a Zepto collection
  • Selector argument for on(evt, selector, fn) can be false
  • Don’t raise error on $('#')
  • Provide empty object in $.support
  • return false in event handler calls stopPropagation()
  • Fix $.isPlainObject() for window in Opera
  • $.ajax error callback correctly reports abort status
  • Fix hasClass in collections of multiple elements
  • Stop iteration in each() when the callback returns false
  • Add ability to set xhr factory per-request
  • Have get() method accept negative index
  • Support for multiple class names in toggleClass()
  • Fix error callbacks for ajaxJSONP
  • Support optional data argument for various Ajax methods
  • Fix DOM insertion operators for null values
  • Fix dataType being set for $.getJSON

v1.0rc1 — 09 Apr 2012 — diff

The semicolon-free edition! That’s right, we removed all trailing semicolons from the source and tests. They were never needed anyway.

New methods:

New module:

  • “selector.js” with experimental support for jQuery CSS pseudo-selectors such as :visible and :first

Improvements in core:

  • added missing methods for Ember.js compatibility
  • improved creating DOM fragments from HTML with $()
  • enable append & family to accept multiple arguments
  • fix $.each context
  • fix calling get without index
  • fix calling val on empty collection
  • using css(property, '') removes the property
  • fix filter, is, and closest when operating on nodes that are detached from the document
  • remove end & andSelf from core to the new “stack.js” plugin
  • exposed important internal Zepto functions through the $.zepto object for extending or overriding Zepto functionality.
  • data method returns undefined when there is no data
  • support camelized names in data method

Apart from improving the basic data method in core, the “data.js” module got improvements as well:

  • better jQuery compatibility
  • ability to store functions
  • new removeData method

Ajax:

  • have correct ajaxComplete argument order for JSONP abort and timeout
  • JSONP requests that hit a 404 will now correctly invoke the error callback
  • add support for dataType: 'jsonp' in $.ajax
  • add support for data in $.ajaxJSONP
  • HTTP 304 status is treated as success instead of an error
  • made load more compatible with jQuery
  • allow Content-Type to be set via request headers
  • respect Content-Type of the response if dataType isn’t set
  • work around Chrome CORS bug when data is empty

Changes in other modules:

  • fix animate for edge cases such as when there is an animation within an animated element, and improve handling of transition CSS properties
  • new “singleTap” event
  • improved “longTap” detection

0.8 — 03 Nov 2011 — diff

  • CSS transitions for every browser with animate() method;
  • unified event handling with fn.on() & off();
  • Ajax global events & timeout support;
  • performance boost for selectors.

See full release notes.

0.7 — 01 Aug 2011 — diff

  • add $.each, $.map, $.slice;
  • add .serializeArray(), .serialize();
  • add .triggerHandler();
  • add .wrap, .wrapAll, .unwrap, .width/height setters, .append (and friends) improvements;
  • add “longTap” event;
  • .anim() accepts CSS transform properties;
  • return false in event handlers cancels browser event behavior.

0.6 — 14 May 2011 — diff

  • add .add, .appendTo, .prependTo, .replaceWith, .empty, .submit;
  • allow function args for .add/.remove/.toggleClass;
  • improvements to events and xhr.

0.5 — 01 Mar 2011 — diff

  • add .not, .children, .siblings, $.param;
  • improve .attr & .html;
  • support callback for .anim.

0.4 — 21 Jan 2011 — diff

  • JSONP;
  • better .find, .each, .closest;
  • add .eq, .size, .parent, .parents, .removeAttr, .val;
  • support function args in .html, .attr;
  • adjacency methods now take Zepto objects.

0.3 — 17 Dec 2010 — diff

  • add .toggleClass, .attr setter, .last, .undelegate, .die;
  • proxied event objects for event delegation;
  • support $ fragments.

0.2 — 01 Dec 2010 — diff

  • now compatible with backbone.js;
  • support event unbind;
  • ajax posts with data.

Acknowledgements & Thanks

A big Thank-You goes out to all of our awesome Zepto.js contributors. May you all forever bask in glory.

The Zepto API is based on jQuery's Core API, which is released under the MIT license.

This documentation is based on the layout of the Backbone.js documentation, which is released under the MIT license.

© 2010-2014 Thomas Fuchs, Freckle Online Time Tracking
Zepto and this documentation is released under the terms of the MIT license.