$.camelCase v1.0+
$.camelCase(string) ⇒ string
Turn a dasherized string into “camel case”. Doesn’t affect already camel-cased strings.
Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API. If you use jQuery, you already know how to use Zepto.
While 100% jQuery coverage is not a design goal, the APIs provided match their jQuery counterparts. The goal is to have a ~5-10k modular library that downloads and executes fast, with a familiar and versatile API, so you can concentrate on getting stuff done.
Zepto is open source software and is released under the developer and business-friendly MIT license.
The default build includes the following modules:
Core, Ajax, Event, Form, IE.
Zepto v1.0 used to bundle Effects, iOS3, and Detect modules in the default build.
See below for
optional modules.
Or grab the latest version on GitHub.
Include Zepto with a script tag near the end of your page:
Zepto will only set the $
global to itself if it is
not yet defined. There is no Zepto.noConflict
method.
If you need to support older browsers, like Internet Explorer 9 and lower, you can fall back to jQuery 1.x.
Note that some optional features of Zepto specifically target mobile browsers; as the original project goal was to specifically provide a leaner alternative to jQuery for the mobile web.
Zepto is a good choice for browser extensions (for Safari, Chrome and Firefox) and to develop HTML-based views within native app frameworks, such as PhoneGap.
In short, Zepto is expected to work in every modern browser and browser-like environment. Zepto doesn't support old Internet Explorer versions (<10).
zepto.js
and zepto.min.js
provided above can be
used as-is. However, for best efficiency and customizability, run the build
system that comes with Zepto's source code.
It allows you to select modules, run tests,
use UglifyJS to
minify your custom build, and gives you an estimate on the compression
that is achievable when zepto.min.js
is served gzipped.
Refer to the README for instructions on how to build Zepto, including running the tests and contributing patches.
module | default | description |
---|---|---|
zepto | ✔ | Core module; contains most methods |
event | ✔ | Event handling via on() & off()
|
ajax | ✔ | XMLHttpRequest and JSONP functionality |
form | ✔ | Serialize & submit web forms |
ie | ✔ | Add support for Internet Explorer 10+ on desktop and Windows Phone 8. |
detect | Provides $.os and $.browser information |
|
fx | The animate() method |
|
fx_methods |
Animated show , hide , toggle ,
and fade*() methods.
|
|
assets | Experimental support for cleaning up iOS memory after removing image elements from the DOM. | |
data |
A full-blown data() method, capable of storing arbitrary
objects in memory.
|
|
deferred |
Provides $.Deferred promises API.
Depends on the "callbacks" module.
When included, $.ajax() supports a
promise interface for chaining callbacks.
|
|
callbacks |
Provides $.Callbacks for use in "deferred" module.
|
|
selector |
Experimental jQuery
CSS extensions support for functionality such as $('div:first') and
el.is(':visible') .
|
|
touch | Fires tap– and swipe–related events on touch devices. This works with both `touch` (iOS, Android) and `pointer` events (Windows Phone). | |
gesture | Fires pinch gesture events on touch devices | |
stack | Provides andSelf & end() chaining methods |
|
ios3 | String.prototype.trim and Array.prototype.reduce methods (if they are missing) for compatibility with iOS 3.x. |
Plugins can be written by adding methods as properties of
$.fn
:
To get started with plug-in development, take a look at the source of Zepto's core module, and be sure to read the coding style guidelines.
$.camelCase(string) ⇒ string
Turn a dasherized string into “camel case”. Doesn’t affect already camel-cased strings.
$.contains(parent, node) ⇒ boolean
Check if the parent node contains the given DOM node. Returns false if both are the same node.
$.each(collection, function(index, item){ ... }) ⇒ collection
Iterate over array elements or object key-value pairs. Returning
false
from the iterator function stops the iteration.
$.extend(target, [source, [source2, ...]]) ⇒ target
$.extend(true, target, [source, ...]) ⇒ target [v1.0]
Extend target object with properties from each of the source objects, overriding the properties on target.
By default, copying is shallow. An optional true
for the first argument
triggers deep (recursive) copying.
Zepto.fn
is an object that holds all of the methods that are available on
Zepto collections, such as addClass()
, attr()
, and
other. Adding a function to this object makes that method available on every
Zepto collection.
Here’s an example implementation of Zepto’s empty()
method:
$.grep(items, function(item){ ... }) ⇒ array
Get a new array containing only the items for which the callback function returned true.
$.inArray(element, array, [fromIndex]) ⇒ number
Get the position of element inside an array, or -1
if not found.
$.isArray(object) ⇒ boolean
True if the object is an array.
$.isFunction(object) ⇒ boolean
True if the object is a function.
$.isPlainObject(object) ⇒ boolean
True if the object is a “plain” JavaScript object, which is only true for object
literals and objects created with new Object
.
$.isWindow(object) ⇒ boolean
True if the object is a window object. This is useful for iframes where each one
has its own window, and where these objects fail the regular obj === window
check.
$.map(collection, function(item, index){ ... }) ⇒ collection
Iterate through elements of collection and return all results of running the
iterator function, with null
and undefined
values filtered out.
$.parseJSON(string) ⇒ object
Alias for the native JSON.parse
method.
$.trim(string) ⇒ string
Remove whitespace from beginning and end of a string; just like String.prototype.trim().
$.type(object) ⇒ string
Get string type of an object. Possible types are: null undefined boolean number string function array date regexp object error.
For other objects it will simply report “object”. To find out if an object is a plain JavaScript object, use isPlainObject.
$(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 performing a CSS selector, wrapping DOM nodes, or creating elements from an HTML string.
A Zepto collection is an array-like object that has chainable methods for
manipulating the DOM nodes it references. All of the methods in this documentation
are collection methods, except the ones directly on the dollar (Zepto
) object,
such as $.extend
.
If a context (CSS selector, DOM node or Zepto collection object) is
given, perform the CSS selector only within nodes of the context; this is
functionally the same as calling $(context).find(selector)
.
When an HTML string is given, use it to create DOM nodes. If an attributes map
is given via argument, apply them to all created elements. For fast single
element creation, use <div>
or <div/>
forms.
When a function is given, attach it as a handler for the DOMContentLoaded
event.
If the page is already loaded, executes the function immediately.
jQuery CSS extensions are not supported. However, the optional "selector" module provides limited support for a few of the most used pseudo-selectors, and can be dropped in for compatibility with existing code or plugins.
Zepto will only set the $
global to itself if it is not yet defined.
This allows you to use Zepto with legacy code that uses, for example,
Prototype.js. Just load Prototype first, and Zepto will not touch
Prototype's $
function. Zepto will always set the Zepto
global
to itself.
add(selector, [context]) ⇒ self
Modify the current collection by adding the results of performing the CSS selector on the whole document, or, if context is given, just inside context elements.
addClass(name) ⇒ self
addClass(function(index, oldClassName){ ... }) ⇒ self
Add class name to each of the elements in the collection. Multiple class names can be given in a space-separated string.
after(content) ⇒ self
Add content to the DOM after each elements in the collection. The content can be an HTML string, a DOM node or an array of nodes.
append(content) ⇒ self
Append content to the DOM inside each individual element in the collection. The content can be an HTML string, a DOM node or an array of nodes.
appendTo(target) ⇒ self
Append elements from the current collection to the target element. This is like append, but with reversed operands.
attr(name) ⇒ string
attr(name, value) ⇒ self
attr(name, function(index, oldValue){ ... }) ⇒ self
attr({ name: value, name2: value2, ... }) ⇒ self
Read or set DOM attributes. When no value is given, reads specified attribute from the first element in the collection. When value is given, sets the attribute to that value on each element in the collection. When value is null, the attribute is removed (like with removeAttr). Multiple attributes can be set by passing an object with name-value pairs.
To read DOM properties such as checked
or selected
, use prop.
before(content) ⇒ self
Add content to the DOM before each element in the collection. The content can be an HTML string, a DOM node or an array of nodes.
children([selector]) ⇒ collection
Get immediate children of each element in the current collection. If selector is given, filter the results to only include ones matching the CSS selector.
clone() ⇒ collection
Duplicate all elements in the collection via deep clone.
This method doesn't have an option for copying data and event handlers over to the new elements, as it has in jQuery.
closest(selector, [context]) ⇒ collection
closest(collection) ⇒ collection [v1.0]
closest(element) ⇒ collection [v1.0]
Traverse upwards from the current element to find the first element that
matches the selector. If context node is given, consider only elements that are
its descendants. This method is similar to parents(selector)
, but
it only returns the first ancestor matched.
If a Zepto collection or element is given, the resulting element will have to match one of the given elements instead of a selector.
concat(nodes, [node2, ...]) ⇒ self
Modify the collection by adding elements to it. If any of the arguments is an array, its elements are merged into the current collection.
This is a Zepto-provided method that is not part of the jQuery API.
contents() ⇒ collection
Get the children of each element in the collection, including text and comment nodes.
css(property) ⇒ value
css([property1, property2, ...]) ⇒ object [v1.1]
css(property, value) ⇒ self
css({ property: value, property2: value2, ... }) ⇒ self
Read or set CSS properties on DOM elements. When no value is given, returns the CSS property from the first element in the collection. When a value is given, sets the property to that value on each element of the collection.
Multiple properties can be retrieved at once by passing an array of property names. Multiple properties can be set by passing an object to the method.
When a value for a property is blank (empty string, null, or undefined), that property is removed. When a unitless number value is given, “px” is appended to it for properties that require units.
data(name) ⇒ value
data(name, value) ⇒ self
Read or write data-*
DOM attributes. Behaves like attr, but prepends
data-
to the attribute name.
When reading attribute values, the following conversions apply: v1.0+
Zepto's basic implementation of `data()` only stores strings. To store arbitrary objects, include the optional "data" module in your custom build of Zepto.
each(function(index, item){ ... }) ⇒ self
Iterate through every element of the collection. Inside the iterator function,
this
keyword refers to the current item (also passed as the second argument to
the function). If the iterator function returns false
, iteration stops.
empty() ⇒ self
Clear DOM contents of each element in the collection.
eq(index) ⇒ collection
Get the item at position specified by index from the current collection.
filter(selector) ⇒ collection
filter(function(index){ ... }) ⇒ collection [v1.0]
Filter the collection to contain only items that match the CSS selector.
If a function is given, return only elements for which the function
returns a truthy value. Inside the function, the this
keyword refers to
the current element.
For the opposite, see not.
find(selector) ⇒ collection
find(collection) ⇒ collection [v1.0]
find(element) ⇒ collection [v1.0]
Find elements that match CSS selector executed in scope of nodes in the current collection.
If a Zepto collection or element is given, filter those elements down to only ones that are descendants of element in the current collection.
first() ⇒ collection
Get the first element of the current collection.
forEach(function(item, index, array){ ... }, [context])
Iterate through every element of the collection. Similar to each, but
the arguments for the iterator functions are different, and returning false
from the iterator won’t stop the iteration.
This is a Zepto-provided method that is not part of the jQuery API.
get() ⇒ array
get(index) ⇒ DOM node
Get all elements or a single element from the current collection. When no index is given, returns all elements in an ordinary array. When index is specified, return only the element at that position. This is different than eq in the way that the returned node is not wrapped in a Zepto collection.
has(selector) ⇒ collection
has(node) ⇒ collection
Filter the current collection to include only elements that have any number of descendants that match a selector, or that contain a specific DOM node.
hasClass(name) ⇒ boolean
Check if any elements in the collection have the specified class.
height() ⇒ number
height(value) ⇒ self
height(function(index, oldHeight){ ... }) ⇒ self
Get the height of the first element in the collection; or set the height of all elements in the collection.
hide() ⇒ self
Hide elements in this collection by setting their display
CSS property to
none
.
html() ⇒ string
html(content) ⇒ self
html(function(index, oldHtml){ ... }) ⇒ self
Get or set HTML contents of elements in the collection. When no content given, returns innerHTML of the first element. When content is given, use it to replace contents of each element. Content can be any of the types described in append.
index([element]) ⇒ number
Get the position of an element. When no element is given, returns position of
the current element among its siblings. When an element is given, returns its
position in the current collection. Returns -1
if not found.
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.
This is a Zepto-provided method that is not part of the jQuery API.
insertAfter(target) ⇒ self
Insert elements from the current collection after the target element in the DOM. This is like after, but with reversed operands.
insertBefore(target) ⇒ self
Insert elements from the current collection before each of the target elements in the DOM. This is like before, but with reversed operands.
is(selector) ⇒ boolean
Check if the first element of the current collection matches the CSS selector.
For basic support of jQuery’s non-standard pseudo-selectors such as :visible
,
include the optional “selector” module.
jQuery CSS extensions are not supported. The optional "selector" module only provides limited support for few of the most used ones.
last() ⇒ collection
Get the last element of the current collection.
map(function(index, item){ ... }) ⇒ collection
Iterate through all elements and collect the return values of the iterator
function. Inside the iterator function, this
keyword refers to the current
item (also passed as the second argument to the function).
Returns a collection of results of iterator function, with null
and
undefined
values filtered out.
next() ⇒ collection
next(selector) ⇒ collection [v1.0]
Get the next sibling–optionally filtered by selector–of each element in the collection.
not(selector) ⇒ collection
not(collection) ⇒ collection
not(function(index){ ... }) ⇒ collection
Filter the current collection to get a new collection of elements that don’t
match the CSS selector. If another collection is given instead of selector,
return only elements not present in it. If a function is given, return only
elements for which the function returns a falsy value. Inside the function,
the this
keyword refers to the current element.
For the opposite, see filter.
offset() ⇒ object
offset(coordinates) ⇒ self [v1.0]
offset(function(index, oldOffset){ ... }) ⇒ self [v1.0]
Get position of the element in the document. Returns an object with properties:
top
, left
, width
and height
.
When given an object with properties left
and top
, use those values to
position each element in the collection relative to the document.
offsetParent() ⇒ collection
Find the first ancestor element that is positioned, meaning its CSS position
value is “relative”, “absolute” or “fixed”.
parent([selector]) ⇒ collection
Get immediate parents of each element in the collection. If CSS selector is given, filter results to include only ones matching the selector.
parents([selector]) ⇒ collection
Get all ancestors of each element in the collection. If CSS selector is given, filter results to include only ones matching the selector.
To get only immediate parents, use parent. To only get the first ancestor that matches the selector, use closest.
pluck(property) ⇒ array
Get values from a named property of each element in the collection, with null
and undefined
values filtered out.
This is a Zepto-provided method that is not part of the jQuery API.
position() ⇒ object
Get the position of the first element in the collection, relative to the offsetParent. This information is useful when absolutely positioning an element to appear aligned with another.
Returns an object with properties: top
, left
.
prepend(content) ⇒ self
Prepend content to the DOM inside each element in the collection. The content can be an HTML string, a DOM node or an array of nodes.
prependTo(target) ⇒ self
Prepend elements of the current collection inside each of the target elements. This is like prepend, only with reversed operands.
prev() ⇒ collection
prev(selector) ⇒ collection [v1.0]
Get the previous sibling–optionally filtered by selector–of each element in the collection.
prop(name) ⇒ value
prop(name, value) ⇒ self
prop(name, function(index, oldValue){ ... }) ⇒ self
Read or set properties of DOM elements. This should be preferred over attr in
case of reading values of properties that change with user interaction over
time, such as checked
and selected
.
Short and lowercase names such as for
, class
, readonly
and similar will be
mapped to actual properties such as htmlFor
, className
, readOnly
, etc.
push(element, [element2, ...]) ⇒ self
Add elements to the end of the current collection.
This is a Zepto-provided method that is not part of the jQuery API.
ready(function($){ ... }) ⇒ self
Attach an event handler for the “DOMContentLoaded” event that fires when the DOM on the page is ready. It’s recommended to use the $() function instead of this method.
reduce(function(memo, item, index, array){ ... }, [initial]) ⇒ value
Identical to Array.reduce that iterates over current collection.
This is a Zepto-provided method that is not part of the jQuery API.
remove() ⇒ self
Remove elements in the current collection from their parent nodes, effectively detaching them from the DOM.
removeAttr(name) ⇒ self
Remove the specified attribute from all elements in the collection. Multiple attributes to remove can be passed as a space-separated list.
removeClass([name]) ⇒ self
removeClass(function(index, oldClassName){ ... }) ⇒ self
Remove the specified class name from all elements in the collection. When the class name isn’t given, remove all class names. Multiple class names can be given in a space-separated string.
replaceWith(content) ⇒ self
Replace each element in the collection–both its contents and the element itself–with the new content. Content can be of any type described in before.
scrollLeft() ⇒ number
scrollLeft(value) ⇒ self
Gets or sets how many pixels were scrolled to the right so far on window or scrollable element on the page.
scrollTop() ⇒ number
scrollTop(value) ⇒ self [v1.1]
Gets or sets how many pixels were scrolled down so far on window or scrollable element on the page.
show() ⇒ self
Restore the default value for the “display” property of each element in the array, effectively showing them if they were hidden with hide.
siblings([selector]) ⇒ collection
Get all sibling nodes of each element in the collection. If CSS selector is specified, filter the results to contain only elements that match the selector.
size() ⇒ number
Get the number of elements in this collection.
slice(start, [end]) ⇒ array
Extract the subset of this array, starting at start
index. If end
is
specified, extract up to but not including end
index.
text() ⇒ string
text(content) ⇒ self
text(function(index, oldText){ ... }) ⇒ self [v1.1.4]
Get or set the text content of elements in the collection. When no content is given, returns the text content of the first element in the collection. When content is given, uses it to replace the text contents of each element in the collection. This is similar to html, with the exception it can’t be used for getting or setting HTML.
toggle([setting]) ⇒ self
Toggle between showing and hiding each of the elements, based on whether the
first element is visible or not. If setting
is present, this method behaves
like show if setting is truthy or hide otherwise.
toggleClass(names, [setting]) ⇒ self
toggleClass(function(index, oldClassNames){ ... }, [setting]) ⇒ self
Toggle given class names (space-separated) in each element in the collection.
The class name is removed if present on an element; otherwise it’s added. If
setting
is present, this method behaves like addClass if setting
is truthy or removeClass otherwise.
unwrap() ⇒ self
Remove immediate parent nodes of each element in the collection and put their children in their place. Basically, this method removes one level of ancestry while keeping current elements in the DOM.
val() ⇒ string
val(value) ⇒ self
val(function(index, oldValue){ ... }) ⇒ self
Get or set the value of form controls. When no value is given, return
the value of the first element. For <select multiple>
, an array of values
is returend. When a value is given, set all elements to this value.
width() ⇒ number
width(value) ⇒ self
width(function(index, oldWidth){ ... }) ⇒ self
Get the width of the first element in the collection; or set the width of all elements in the collection.
wrap(structure) ⇒ self
wrap(function(index){ ... }) ⇒ self [v1.0]
Wrap each element of the collection separately in a DOM structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node, or as a function that is called for each element and returns one of the first two types.
Keep in mind that wrapping works best when operating on nodes that are part
of the DOM. When calling wrap()
on a new element and then inserting the result
in the document, the element will lose the wrapping.
wrapAll(structure) ⇒ self
Wrap all elements in a single structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node.
wrapInner(structure) ⇒ self
wrapInner(function(index){ ... }) ⇒ self [v1.0]
Wrap the contents of each element separately in a structure. Structure can be a single element or several nested elements, and can be passed in as a HTML string or DOM node, or as a function that is called for each element and returns one of the first two types.
The “detect” module is useful to fine-tune your site or app to different environments, and helps you to discern between phone and tablets; as well as different browser engines and operating system versions.
$.Event(type, [properties]) ⇒ event
Create and initialize a DOM event of the specified type. If a properties object
is given, use it to extend the new event object. The event is configured to
bubble by default; this can be turned off by setting the bubbles
property to false
.
An event initialized with this function can be triggered with trigger.
$.proxy(fn, context) ⇒ function
$.proxy(fn, context, [additionalArguments...]) ⇒ function [v1.1.4]
$.proxy(context, property) ⇒ function
$.proxy(context, property, [additionalArguments...]) ⇒ function [v1.1.4]
Get a function that ensures that the value of this
in the original function
refers to the context object. In the second form, the original function is read
from the specific property of the context object.
If additional arguments are passed beyond the 2nd argument, they are applied to every invocation of the wrapped function in front of its actual arguments.
Deprecated, use on instead.
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]
Attach an event handler to elements.
Deprecated, use on instead.
delegate(selector, type, function(e){ ... }) ⇒ self
delegate(selector, { type: handler, type2: handler2, ... }) ⇒ self
Attach an event handler that is only triggered when the event originated from a node that matches a selector.
Deprecated, use off instead.
die(type, function(e){ ... }) ⇒ self
die({ type: handler, type2: handler2, ... }) ⇒ self
Detach event handler added by live.
event.isDefaultPrevented() ⇒ boolean
Returns true if preventDefault()
was called for this event instance. This
serves as a cross-platform alternative to the native defaultPrevented
property
which is missing or unreliable in some browsers.
event.isImmediatePropagationStopped() ⇒ boolean
Returns true if stopImmediatePropagation()
was called for this event instance.
Zepto implements the native method in browsers that don’t support it (e.g. old
versions of Android).
event.isPropagationStopped() ⇒ boolean
Returns true if stopPropagation()
was called for this event instance.
Deprecated, use on instead.
live(type, function(e){ ... }) ⇒ self
live({ type: handler, type2: handler2, ... }) ⇒ self
Like delegate where the selector is taken from the current collection.
off(type, [selector], function(e){ ... }) ⇒ self
off({ type: handler, type2: handler2, ... }, [selector]) ⇒ self
off(type, [selector]) ⇒ self
off() ⇒ self
Detach event handlers added with on. To detach a specific event handler,
the same function must be passed that was used for on()
. Otherwise, just
calling this method with an event type will detach all handlers of that type.
When called without arguments, it detaches all event handlers registered on
current elements.
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 collection. Multiple event types can be passed in a space-separated string, or as an object where event types are keys and handlers are values. If a CSS selector is given, the handler function will only be called when an event originates from an element that matches the selector.
If the data
argument is given, this value will be made available as the
event.data
property during the execution of the event handler.
Event handlers are executed in the context of the element to which the handler
is attached, or the matching element in case a selector is provided. When an
event handler returns false
, preventDefault()
and stopPropagation()
is called for the current
event, preventing the default browser action such as following links.
If false
is passed as argument to this method in place of the callback
function, it’s equivalent to passing a function that returns false
.
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]
Adds an event handler that removes itself the first time it runs, ensuring that
the handler only fires once. See .on()
for the explanation of
selector
and data
arguments.
trigger(event, [args]) ⇒ self
Trigger the specified event on elements of the collection. Event can either be a string type, or a full event object obtained with $.Event. If an args array is given, it is passed as additional arguments to event handlers.
Zepto only supports triggering events on DOM elements.
triggerHandler(event, [args]) ⇒ self
Like trigger, but triggers only event handlers on current elements and doesn’t bubble.
Deprecated, use off instead.
unbind(type, function(e){ ... }) ⇒ self
unbind({ type: handler, type2: handler2, ... }) ⇒ self
Detach event handler added with bind.
Deprecated, use off instead.
undelegate(selector, type, function(e){ ... }) ⇒ self
undelegate(selector, { type: handler, type2: handler2, ... }) ⇒ self
Detach event handler added with delegate.
$.ajax(options) ⇒ XMLHttpRequest
Perform an Ajax request. It can be to a local resource, or cross-domain via HTTP access control support in browsers or JSONP.
Options:
type
(default: “GET”): HTTP request method (“GET”, “POST”, or other)url
(default: current URL): URL to which the request is madedata
(default: none): data for the request; for GET requests it is appended
to query string of the URL. Non-string objects will get serialized with
$.paramprocessData
(default: true): whether to automatically serialize data
for
non-GET requests to stringcontentType
(default: “application/x-www-form-urlencoded”): the Content-Type
of the data being posted to the server (this can also be set via headers
).
Pass false
to skip setting the default value.mimeType
(default: none): override the MIME type of the response.
v1.1+dataType
(default: none): response type to expect from the server. One of
json
, jsonp
, script
, xml
, html
, or text
.jsonp
(default: “callback”): the name of the JSONP callback query parameterjsonpCallback
(default: “jsonp{N}”): the string (or a function that returns)
name of the global JSONP callback function. Set this to enable browser caching.
v1.1+timeout
(default: 0
): request timeout in milliseconds, 0
for no timeoutheaders
: object of additional HTTP headers for the Ajax requestasync
(default: true): set to false
to issue a synchronous (blocking) requestglobal
(default: true): trigger global Ajax events on this requestcontext
(default: window): context to execute callbacks intraditional
(default: false): activate traditional (shallow) serialization
of data
parameters with $.paramcache
(default: true): whether the browser should be allowed to cache GET responses.
Since v1.1.4, the default is false
for
dataType: "script"
or jsonp
.xhrFields
(default: none): an object containing properties to be copied over
verbatim to the XMLHttpRequest instance.
v1.1+username
& password
(default: none): HTTP Basic authentication credentials.
v1.1+If the URL contains =?
or dataType
is “jsonp”, the request is performed
by injecting a <script>
tag instead of using XMLHttpRequest (see JSONP).
This has the limitation of contentType
, dataType
, headers
, and async
not
being supported.
You can specify the following callback functions, which are given in order of execution:
beforeSend(xhr, settings)
: before the request is sent. Provides access to
the xhr object and allows changing the settings.
Return false
from the function to cancel the request
success(data, status, xhr)
: when request succeeds
error(xhr, errorType, error)
: if there is an error (timeout, parse error,
or status code not in HTTP 2xx)
complete(xhr, status)
: after the request is complete, regardless of error
or success
If the optional modules “callbacks” and “deferred” are loaded, the XHR object
returned from $.ajax()
calls implements a promise interface for adding
callbacks by chaining:
These methods supersede the success
, error
, and complete
callback options.
These events are fired during the lifecycle of an Ajax request performed with
the default setting of global: true
:
ajaxStart
(global): fired if no other Ajax requests are currently
active
ajaxBeforeSend
(xhr, options): before sending the request; can be
cancelled
ajaxSend
(xhr, options): like ajaxBeforeSend
, but not cancellable
ajaxSuccess
(xhr, options, data): when the response is success
ajaxError
(xhr, options, error): when there was an error
ajaxComplete
(xhr, options): after request has completed, regardless
of error or success
ajaxStop
(global): fired if this was the last active Ajax request
By default, Ajax events are fired on the document object. However, if the
context
of a request is a DOM node, the events are fired on that node and will
bubble up the DOM. The only exceptions to this are the global events ajaxStart
& ajaxStop
.
Deprecated, use $.ajax instead.
$.ajaxJSONP(options) ⇒ mock XMLHttpRequest
Perform a JSONP request to fetch data from another domain.
This method has no advantages over $.ajax and should not be used.
Object containing the default settings for Ajax requests. Most settings are described in $.ajax. The ones that are useful when set globally are:
timeout
(default: 0
): set to a non-zero value to specify a default timeout
for Ajax requests in millisecondsglobal
(default: true): set to false to prevent firing Ajax eventsxhr
(default: XMLHttpRequest factory): set to a function that returns
instances of XMLHttpRequest (or a compatible object)accepts
: MIME types to request from the server for specific dataType
values:
$.get(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
$.get(url, [data], [function(data, status, xhr){ ... }], [dataType]) ⇒ XMLHttpRequest [v1.0]
Perform an Ajax GET request. This is a shortcut for the $.ajax method.
$.getJSON(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
$.getJSON(url, [data], function(data, status, xhr){ ... }) ⇒ XMLHttpRequest [v1.0]
Get JSON data via Ajax GET request. This is a shortcut for the $.ajax method.
$.param(object, [shallow]) ⇒ string
$.param(array) ⇒ string
Serialize an object to a URL-encoded string representation for use in Ajax request query strings and post data. If shallow is set, nested objects are not serialized and nested array values won’t use square brackets on their keys.
If any of the individual value objects is a function instead of a string, the function will get invoked and its return value will be what gets serialized.
This method accepts an array in serializeArray format, where each item has “name” and “value” properties.
$.post(url, [data], function(data, status, xhr){ ... }, [dataType]) ⇒ XMLHttpRequest
Perform an Ajax POST request. This is a shortcut for the $.ajax method.
data
can also be a string:
load(url, function(data, status, xhr){ ... }) ⇒ self
Set the html contents of the current collection to the result of a GET Ajax call to the given URL. Optionally, a CSS selector can be specified in the URL, like so, to use only the HTML content matching the selector for updating the collection:
If no CSS selector is given, the complete response text is used instead.
Note that any JavaScript blocks found are only executed in case no selector is given.
serialize() ⇒ string
Serialize form values to an URL-encoded string for use in Ajax post requests.
serializeArray() ⇒ array
Serialize form into an array of objects with name
and value
properties.
Disabled form controls, buttons, and unchecked radio buttons/checkboxes are skipped.
The result doesn’t include data from file inputs.
submit() ⇒ self
submit(function(e){ ... }) ⇒ self
Trigger or attach a handler for the submit event. When no function given,
trigger the “submit” event on the current form and have it perform its submit
action unless preventDefault()
was called for the event.
When a function is given, this simply attaches it as a handler for the “submit” event on current elements.
Global settings for animations:
$.fx.off
(default false in browsers that support CSS transitions): set to
true to disable all animate()
transitions.
$.fx.speeds
: an object with duration settings for animations:
_default
(400 ms)fast
(200 ms)slow
(600 ms)Change existing values or add new properties to affect animations that use a string for setting duration.
animate(properties, [duration, [easing, [function(){ ... }]]]) ⇒ self
animate(properties, { duration: msec, easing: type, complete: fn }) ⇒ self
animate(animationName, { ... }) ⇒ self
Smoothly transition CSS properties of elements in the current collection.
properties
: object that holds CSS values to animate to; or CSS keyframe
animation nameduration
(default 400): duration in milliseconds, or a string:
fast
(200 ms)slow
(600 ms)$.fx.speeds
easing
(default linear
): specifies the type of animation easing to use, one of:
ease
linear
ease-in
/ ease-out
ease-in-out
cubic-bezier(...)
complete
: callback function for when the animation finishesdelay
: transition delay in milliseconds
v1.1+Zepto also supports the following CSS transform properties:
translate(X|Y|Z|3d)
rotate(X|Y|Z|3d)
scale(X|Y|Z)
matrix(3d)
perspective
skew(X|Y)
If the duration is 0
or $.fx.off
is true (default in a browser that doesn’t
support CSS transitions), animations will not be executed; instead the target
values will take effect instantly. Similarly, when the target CSS properties
match the current state of the element, there will be no animation and the
complete
function won’t be called.
If the first argument is a string instead of object, it is taken as a CSS keyframe animation name.
Zepto exclusively uses CSS transitions for effects and animation. jQuery easings are not supported. jQuery's syntax for relative changes ("=+10px") is not supported. See the spec for a list of animatable properties. Browser support may vary, so be sure to test in all browsers you want to support.
The “touch” module adds the following events, which can be used with on and off:
tap
— fires when the element is tapped.singleTap
and doubleTap
— this pair of events can be used to detect both single and double taps on the same element (if you don’t need double tap detection, use tap
instead).longTap
— fires when an element is tapped and the finger is held down for more than 750ms.swipe
, swipeLeft
, swipeRight
, swipeUp
, swipeDown
— fires when an element is swiped (optionally in the given direction)All these events are also available via shortcut methods on any Zepto collection.
See the change log on Github.
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-2016 Thomas Fuchs, Freckle Online Time Tracking
Zepto and this documentation is released under the terms of the MIT license.