Zepto.js

Zepto It's a lightweight For modern advanced browsers JavaScript library , It and jquery Have a similar api. If you can use jquery, Then you can use zepto.

Zepto The purpose of the design is Provide jQuery Similar API, But not 100% Cover jQuery .Zepto The purpose of the design is to have a 5-10k General library 、 Download and quickly execute 、 Have a familiar general API, So you can put you The main focus is on Application Development .

Zepto Is an open source software , It can be released by developers and businesses . MIT license.

Download Zepto

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

Zepto v1.0 The default binding Effects, iOS3, and Detect modular .
See below Optional modules (optional modules).

Or grab the latest version on GitHub.

Use a script Label introduction Zepto Go to the bottom of your page :

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

If $ The variable has not been defined ,Zepto Set only global variables $ Point to itself . No, Zepto.noConflict method .

If you need to support old browsers , as Internet Explorer 9 Or below , You can return to jQuery of 1.x.

Browser support

Elementary (100% support )

Secondary goals ( Full or majority support )

It should be noted that Zepto Some of the optional functions of are specifically for mobile browsers ; Because its original goal is to provide a streamlined similar service on the mobile end jquery of js library .

On the browser (Safari、Chrome and Firefox) Develop a web application or build a web application based on html of web-view Local application , You are like PhoneGap, use Zepto It's a good choice .

in short ,Zepto Hope to be used as a basic environment in all modern browsers .Zepto Older versions of... Are not supported Internet Explorer browser (<10).

Manually create Zepto

zepto.js and zepto.min.js Provide the above methods of use . however , For better program effect and freedom , Can be used in Zepto Source code construction Zepto.js and zepto.min.js Select the module and test it , use UglifyJS Generate... According to your needs ( When the server is turned on gzipped after , The most streamlined code ) code .

About how to build Zepto of the README, Includes running tests and patches .

Zepto modular

module default description
zepto Core module ; Contains many methods
event Through on()& off() Handling events
ajax XMLHttpRequest and JSONP Practical functions
form Serialize & Submit web form
ie Add desktop support Internet Explorer 10+ and Windows Phone 8.
detect Provide $.os and $.browser news
fx The animate() method
fx_methods In animated form show, hide, toggle, and fade*() method .
assets Experimental support from DOM Remove image Clean up after element iOS Memory .
data A comprehensive data() method , Can store any object in memory .
deferred Provide $.Deferredpromises API. Rely on "callbacks" modular .
When this module is included , $.ajax() support promise Interface chained callback .
callbacks by "deferred" The module provides $.Callbacks.
selector Experimental support jQuery CSS expression Practical functions , such as $('div:first') and el.is(':visible').
touch Trigger on touch device tap– and swipe– Related events . This applies to all `touch`(iOS, Android) and `pointer` event (Windows Phone).
gesture Trigger on touch device pinch Gesture Events .
stack Provide andSelf& end() Chain call method
ios3 String.prototype.trim and Array.prototype.reduce method ( If they don't exist ) , To be compatible with iOS 3.x.

Create plug-ins

You can add methods as $.fn To write the plug-in :

;(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 plug-ins , Take a look at source of Zepto's core module, And confirm that you have read coding style guidelines


Core method

$()

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

By executing css selector , packing dom node , Or through a html String creates multiple elements To create a Zepto Collection objects .

Zepto A collection is an array like object , It has a chained method to manipulate what it points to DOM node , Except $( Zepto) Object ( as $.extend), All methods in the document object are collection methods .

If present in the selector content parameter (css selector ,dom, Or Zepto Collection objects ), Then only in the context of the given node css selector ; This function and use $(context).find(selector) It's the same .

When given a html String fragment to create a dom Node time . You can also create nodes by giving a set of attribute mappings . Fastest create element , use <div> Or <div/> Form .

When a function is attached to DOMContentLoaded In the process of event processing . If the page has been loaded , This method will be executed immediately .

$('div')  //=>  In all pages div element 
$('#foo') //=> ID  by  "foo"  Elements of 

//  Create element :
$("<p>Hello</p>") //=>  new p element 
//  Create an element with attributes :
$("<p />", { text:"Hello", id:"greeting", css:{color:'darkblue'} })
//=> <p id=greeting style="color:darkblue">Hello</p>

//  When the page ready When I was , Execute callback :
Zepto(function($){
  alert('Ready to Zepto!')
})

I won't support it jQuery CSS Expand , however , Optional “selector” The module is limited and provides support for several of the most commonly used pseudo selectors , And can be discarded , Compatible execution with existing code or plug-ins .

If $ The variable has not been defined ,Zepto Only global variables are set $ Point to itself . Allows you to use both Zepto And useful legacy code , For example ,prototype.js. Just load... First Prototype,Zepto Will not overwrite Prototype of $ function .Zepto The global variable will always be set Zepto Point to itself .

$.camelCase v1.0+

$.camelCase(string)  ⇒ string

Turn a set of strings into “ Camels ” New string for nomenclature , If the character is already “ Camels ” Nomenclature , It doesn't change .

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

$.contains v1.0+

$.contains(parent, node)  ⇒ boolean

Check whether the parent node contains the given dom node , If the two are the same node , Returns false.

$.each

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

Traverse array elements or key-value Traversing objects by value pairs . The callback function returns false Stop traversing .

$.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+

Extend the properties of the target object through the source object , The source object properties override the target object properties .

The default is , Copy as a shallow copy ( Shallow copy ). If the first parameter is true Represents a deep copy ( Deep copy ).

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

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

$.fn

Zepto.fn Is an object , It has Zepto All available methods on the object , as addClass(), attr(), And other methods . Add a method to this object , be-all Zepto This method can be used on all objects .

Here is an implementation Zepto of empty() Examples of methods :

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

$.grep v1.0+

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

Get a new array , The new array contains only... Returned in the callback function ture Array item for .

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

$.inArray v1.0+

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

Returns the index value of the specified element in the array ( Fool's Wharf note : With 0 Is the base ), If the element is not found, it returns -1.

Fool's Wharf note :[fromIndex] Parameters are optional , Indicates which index value to start looking back from .

$.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

If object yes array, Returns ture.

$.isFunction

$.isFunction(object)  ⇒ boolean

If object yes function, Returns ture.

$.isPlainObject v1.0+

$.isPlainObject(object)  ⇒ boolean

Whether the test object is “ Pure ” The object of , This object is through Object constants ("{}") Or new Object Created , If it is , Returns true.

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

$.isWindow v1.0+

$.isWindow(object)  ⇒ boolean

If object Whether the parameter is a window Object , Then return to true. This is dealing with iframe Very useful when , Because everyone iframe They all have their own window Object , Using conventional methods obj === window Check these objects Will fail when .

$.map

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

By traversing the elements in the collection , Returns all the results of the iterated function ,( Fool's Wharf note : A new array )null and undefined Will 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

Primordial JSON.parse Method alias .( Fool's Wharf note : Accept a standard format JSON character string , And return the parsed JavaScript Object .)

$.trim v1.0+

$.trim(string)  ⇒ string

Delete the whitespace at the beginning and end of the string . similar String.prototype.trim().

$.type v1.0+

$.type(object)  ⇒ string

obtain JavaScript Type of object . Possible types are : null undefined boolean number string function array date regexp object error.

For other objects , It is simply reported as “object”, If you want to know whether an object is a javascript Ordinary objects , use isPlainObject.

add

add(selector, [context])  ⇒ self

Add elements to the currently matched element collection . If given content parameter , Will only be in content Element , Otherwise, in the whole document Find .

<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

Add the specified for each matching element class Class name . Multiple class Class names are separated by spaces .

after

after(content)  ⇒ self

Insert content after each matching element ( Fool's Wharf note : External insert ). The content can be html character string ,dom node , Or an array of nodes .

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

append

append(content)  ⇒ self

Insert content at the end of each matching element ( Fool's Wharf note : Internal insert ). The content can be html character string ,dom node , Or an array of nodes .

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

appendTo

appendTo(target)  ⇒ self

Insert the matching element at the end of the target element ( Fool's Wharf note : Internal insert ). This is a bit like append, But the inserted 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

Read or set dom Properties of . If not given value parameter , Then read the attribute value of the first element in the object collection . When given value parameter . Set the value of this attribute for all elements in the object collection . When value The parameter is null, Then this attribute will be removed ( similar removeAttr), Multiple properties can be set through object key value pairs .

To read DOM Properties of, such as checked and selected, use prop.

var form = $('form')
form.attr('action')             //=>  Read value 
form.attr('action', '/create')  //=>  Set value 
form.attr('action', null)       //=>  Remove properties 

//  Multiple attributes :
form.attr({
  action: '/create',
  method: 'post'
})

before

before(content)  ⇒ self

Insert content before matching each element ( Fool's Wharf note : External insert ). The content can be html character string ,dom node , Or an array of nodes .

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

children

children([selector])  ⇒ collection

Get the direct child element of each matching element collection element , If given selector, Then the returned result only contains the information that conforms to css The element of the 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 by deep cloning .

This method does not copy data and event handlers to new elements . This is similar to jquery Using a parameter to determine whether to copy data is different from event processing .

closest

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

Start with the element itself , Match the parent element level by level , And return the first match selector Elements of . If given context Node parameters , Then only the descendant elements of the node are matched . This method is similar to parents(selector) A little similar , But it only returns the first matching ancestor element .

If the parameter is a Zepto A collection of objects or an element , The result must match the given element, not the selector .

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

concat

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

Add element to a Zepto Object collection to form a new array . If the parameter is an array , Then the elements in this array will be merged into Zepto Object collection .

This is a Zepto Methods provided , no jquey of API .

contents v1.0+

contents()  ⇒ collection

Get the child elements of each matching element collection element , Including text and annotation nodes .( Fool's Wharf note :.contents() and .children() The method is similar to , But the former includes text nodes and jQuery Object HTML element .)

css

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

Read or set DOM Elemental css attribute . When value When the parameter does not exist , Returns the name of the first element in the object collection css attribute . When value When the parameter exists , Set the corresponding value of each element in the object collection css attribute .

Multiple attributes can be obtained at one time by passing an array of attribute names . Multiple properties can be set by using object key value pairs .

When value Empty ( Empty string ,null Or undefined), that css Properties will be removed . When value The parameter is a unitless number , If you should css Attribute requires units ,“px” Will be automatically added to this 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 dom of data-* attribute . Act a little like attr , But the attribute name is preceded by data-.

When reading the attribute value , There will be the following conversions :v1.0+

  • “true”, “false”, and “null” Is converted to the corresponding type ;
  • Convert numeric value to actual numeric type ;
  • JSON The value will be parsed , If it works JSON;
  • Everything else is returned as a string .

    Zepto Basically realize `data()` Only strings can be stored . If you want to store any object , Please introduce optional “data” Module to your build Zepto in .

each

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

Traverse a collection of objects, each element . In an iterative function ,this Keyword points to the current item ( Pass... As the second parameter of the function ). If the iterated function returns false, End of traversal .

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

empty

empty()  ⇒ self

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

eq

eq(index)  ⇒ collection

Gets the given index value from the current collection of objects ( Fool's Wharf note : With 0 Is the base ) Elements of .

$('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+

Filter object collection , Returns a collection of objects that meet the css The item of the selector . If the argument is a function , Function returns when there is actual value , Element will be returned . in function , this Keyword points to the current element .

The opposite function , see not.

find

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

Find a match in the current object's front collection CSS Descendants of each element of the selector .

If given Zepto Object collection or element , Filter them , Only if they are present Zepto When in a collection object , Was 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]) 

Traverse each element in the object collection , It's kind of like each, But the parameters of the traversal function are different , When the function returns false When I was , Traversal does not stop .

This is a Zepto Methods provided , no jquery of API.

get

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

Gets all elements or a single element from the current object collection . When index When the parameter does not exist , Return all the elements as a normal array . When specifying index Time , Return only the elements of the set . This is similar to eq Different , The method returns DOM node , no 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 have elements that match the selector , Or whether to include the specified DOM node , If there is , Returns a new collection of objects , This object filters out elements that do not contain selector matches or do not contain the specified DOM Node object .

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

hasClass

hasClass(name)  ⇒ boolean

Checks 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

Gets 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 css Properties of display by none To hide the elements in the object collection .

html

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

Gets or sets the name of the element in the object collection HTML content . When there is no given content Parameter is not valid , Returns the name of the first element in the object collection innerHtml. When given content Parameter is not valid , Replace the contents of each element in the object collection with it .content It can be append All 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,
    '[email protected]<a href="http://twitter.com/$2">$2</a>')
})

index

index([element])  ⇒ number

Get the index value of an element ( Fool's Wharf note : from 0 Start counting ). When elemen When the parameter is not given , Returns the position of the current element in the sibling node . When element When parameters are given , Returns its position in the current collection of objects . If the element is not found , Returns -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 value of an element in the current object collection ( Fool's Wharf note : from 0 Start counting ). If given formindex parameter , Start at this location and look back , Return based on 0 Index value of , If you don't find , Returns -1.index Method is implemented based on this method .

This is a Zepto How to , no jquer of api.

insertAfter

insertAfter(target)  ⇒ self

Inserts the element in the collection after the specified target element ( Fool's Wharf note : External insert ). This is a bit like after, But in the opposite way .

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

insertBefore

insertBefore(target)  ⇒ self

Inserts the element in the collection in front of the specified target element ( Fool's Wharf note : External insert ). This is a bit like before, But in the opposite way .

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

is

is(selector)  ⇒ boolean

Judge whether the first element in the current element set matches css selector . For basic support jquery Nonstandard selectors similar to : :visible Included in the optional “selector” In the module .

jQuery CSS extensions Not supported . choice “selector” Modules can only support a limited number of the most common ways .

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 . Form a new collection object by traversing the return value of the function . In the traversal function this The key points to the item in the current loop ( Traverse the second parameter in the function ).

Traversal returns null and undefined, 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 ( You can optionally bring a filter selector ).

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

not

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

Filter the current collection of objects , Get a new collection of objects , The elements in it can't match css selector . If the other parameter is Zepto Object collection , So the new Zepto None of the elements in the object are contained in the parameter object . If the argument is a function . Contains only functions that execute as false Elements worth the time , Function this Keyword points to the current loop element .

The opposite function , see filter.

offset

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

Gets the current element relative to document Location of . Returns an object containing : top, left, width and height

When a given contains left and top Property object , Use these values to compare each element in the collection document The positioning of .

offsetParent v1.0+

offsetParent()  ⇒ collection

Find the first positioned ancestor element , It means its css In position The attribute value is “relative”, “absolute” or “fixed”

parent

parent([selector])  ⇒ collection

Gets the immediate parent element of each element in the object collection . If css Selector parameters given . Filter out qualified elements .

parents

parents([selector])  ⇒ collection

Get all the ancestor elements of each element in the object collection . If css Selector parameters given , Filter out qualified elements .

If you want to get the direct parent element , use parent. If you only want to get the first match css The element of the selector , use closest.

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

pluck

pluck(property)  ⇒ array

Get the attribute value of each element in the object collection . The return value is null Or undefined It's worth filtering out .

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

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

This is a Zepto How to , no jquery of api

position v1.0+

position()  ⇒ object

Gets the position of the first element in the object collection . be relative to offsetParent. When an absolutely positioned element is close to 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 matching element ( Fool's Wharf note : Insert inside element ). Insert d You can try html String fragment , One dom node , Or an array of nodes .

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

prependTo

prependTo(target)  ⇒ self

Insert all elements in front of the target ( Fool's Wharf note : Insert inside element ). It's kind of like prepend, 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 , Filter through selector .

prop v1.0+

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

Read or set dom Attribute value of element . It takes precedence over... When reading attribute values attr, Because these attribute values will change due to user interaction , as checked and selected.

Short or lowercase name , such as for, class, readonly And similar properties , Will be mapped to the actual properties , such as htmlFor, className, readOnly, wait .

push

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

Add elements to the end of the current collection.

Adds an element to the last of the current collection of objects .

This is a zepto How to , no jquery of api

ready

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

Add an event listener , When the page DOM Loading complete “DOMContentLoaded” When an event is triggered . It is recommended to use $() To replace this usage .

reduce

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

And Array.reduce Have the same usage , Traverse the current collection of objects .memo Is the last return value of the function . Iterate through .

This is a zepto How to , no jquery of api

remove

remove()  ⇒ self

Deletes the element in the current collection from its parent node , Effectively from dom Remove .

removeAttr

removeAttr(name)  ⇒ self

Removes the specified attributes of all elements in the current object collection .

removeClass

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

Removes the specified of all elements in the current object collection class. If not specified name parameter , Remove all class. Multiple class Parameter names can be separated by spaces . The following example removes two class.

<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 matching elements with the given content .( Contains the element itself ).content The parameter can be before Types described in .

scrollLeft v1.1+

scrollLeft()  ⇒ number
scrollLeft(value)  ⇒ self

Gets or sets the pixel value of the scrolling element on the page or the right scrolling of the entire window .

scrollTop v1.0+

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

Gets or sets the pixel value of the scrolling element on the page or the scrolling down of the entire window .

show

show()  ⇒ self

Restores the default value of each element in the object collection “display” Worth . If you use hide Hide elements , Use this property to display it . It's equivalent to removing display:none.

siblings

siblings([selector])  ⇒ collection

Gets the sibling node of all elements in the object collection . If given CSS Selector parameters , 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 array array Subset of , from start start , If given end, Extract from start Start to end End element , But it doesn't include end Element of position .

text

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

Gets or sets the text content of elements in all object collections . When there is no given content Parameter is not valid , Returns the text content of the first element in the current object collection ( Contains the text content in the child nodes ). When given content Parameter is not valid , Use it to replace the text content of all elements in the object collection . It looks like html, Unlike it, it cannot be used to get or set HTML.

toggle

toggle([setting])  ⇒ self

Show or hide matching elements . If setting by true, amount to show method . If setting by false. amount to hide method .

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 matching element collection . If class If the name of exists, delete it , If it doesn't exist , Just add it . If setting The value of is true , This function is similar to addClass, If false , This function is similar to removeClass.

unwrap

unwrap()  ⇒ self

Remove the immediate parent node of each element in the collection , And keep their child elements in their original positions . Basically , This method deletes the previous ancestor element , While maintaining DOM The current element in the .

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

Gets or sets the value of the matching element . When there is no given value parameter , Returns the value of the first element . If it is <select multiple> label , Returns an array . When given value parameter , Then the values of all elements will be set .

width

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

Gets 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+

Put a... On the outer package of each matching element html element .structure Parameters can be a single element or some nested elements . It can also be a html String fragment or dom node . It can also be a callback function that generates package elements , This function returns the first two types of parcel fragments .

What needs to be reminded is : This method is useful for dom Nodes in have good support . If you will wrap() Used on a new element , Then insert the result into document in , The method is invalid at this time .

// 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

There is a separate structure outside all matching elements . The structure can be a single element or Several nested elements , And can be used as HTML String or 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+

Put... In each element content Wrapped in a separate structure . The structure can be a single component or multiple nested components , And can be used as HTML String or DOM node , Or a callback function that generates package elements , This function returns the first two types of parcel fragments .

// 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 can fine tune your site or application in different environments , And help you identify your phone and tablet ; And 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]

//  Besides , Version information is available .
//  Here's how to run ​​iOS 6.1 of iPhone Returned .
!!$.os.phone         // => true
!!$.os.iphone        // => true
!!$.os.ios           // => true
$.os.version       // => "6.1"
$.browser.version  // => "536.26"

Event handling

$.Event

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

Creates and initializes a specified DOM event . If given properties Object , Use it to extend new event objects . By default , Event is set to bubble mode ; This can be set by bubbles by false To close .

An event initialization function can use trigger To 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 , Then return a new function , And the new function always maintains a specific context (context) Context , In the new function this Point to context parameter . Another form , original function From the context (context) Object's specific properties .

If the delivery exceeds 2 Additional parameters for , They are used for Pass on to fn Parameter function quote .

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 🐶🔫

Not recommended , use on replace .

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+

Bind a processing event for an element .

delegate 🐶🔫

Not recommended , use on replace .

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

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

die 🐶🔫

Not recommended , use on replace .

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

Delete through live Added event .

event.isDefaultPrevented v1.1+

event.isDefaultPrevented()  ⇒ boolean

If preventDefault() Called by an instance of this event , Then return to true. This can be used as a cross platform alternative to native defaultPrevented attribute , If defaultPrevented 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

If stopImmediatePropagation() Called by an instance of this event , Then return to true.Zepto Implement this native method in browsers that do not support it , ( For example, the old version Android).

event.isPropagationStopped v1.1+

event.isPropagationStopped()  ⇒ boolean

If stopPropagation() Called by an instance of this event , Then return to true.

live 🐶🔫

Not recommended , use on replace .

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

similar delegate, Add event handlers to match all elements of the current selector , 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 through on Added event . Remove a specific event handler , You must use on() The same function added . Otherwise , Calling this method only through an event type will remove all handlers of that type . If there are no parameters , Move out of the current element All Registration event for .

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 an event handler to an element in the object collection . Multiple events can be added as strings of spaces , Or take the event type as the key 、 An object valued by a function Way . If given css selector , When an event is initiated on an element that matches the selector , The event will be triggered ( Fool's Wharf note : Event delegation , Or event agent ).

If given data parameter , This value will be used as a useful... During the execution of the event handler event.data attribute

The event handler is adding the element of the handler 、 Or in the context of an element that matches the selector in the case of a given selector ( Fool's Wharf note :this Point to the element that triggers the event ). When an event handler returns false,preventDefault() and stopPropagation() When called by the current event , Will prevent default browser actions , Such as link .

If false Pass this method as a parameter at the location of the callback function , It's equivalent to passing a function , This function returns directly false.( Fool's Wharf note : soon false As function(e){ ... } Parameters of , As function(){ return false; } Short 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 a handle event to the element , After the first execution of the event , This event will automatically unbind , Ensure that the processing function executes on each element at most once .selector and data Please check the parameter description .on().

trigger

trigger(event, [args])  ⇒ self

Triggers the specified event on the element of the object collection . The event can be a string type , It can also be a Through $.Event Defined event object . If given args parameter , It is passed as a parameter 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 supported in dom Event triggered on element .

triggerHandler

triggerHandler(event, [args])  ⇒ self

image trigger, It only triggers events on the current element , But it doesn't bubble .


        $("input").triggerHandler('focus');
        //  here input On the focus Event triggers , however input Will not get focus 
        $("input").trigger('focus');
        //  here input On the focus Event triggers ,input Get focus 

unbind 🐶🔫

Deprecated, use off instead.

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

Remove through bind Registered events .

undelegate 🐶🔫

Deprecated, use off instead.

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

Remove through delegate Registered events .


Ajax request

$.ajax

$.ajax(options)  ⇒ XMLHttpRequest

Execute Ajax request . It can be a local resource , Or by supporting HTTP access control Browser for Or through JSONP To achieve cross domain .

option :

  • type( By default : “GET”): Request method (“GET”, “POST”, or other)
  • url ( By default : Current address ): Address to send the request
  • data ( By default :none): Data sent to server ; If it is GET request , It will be automatically spliced as a parameter to url upper . wrong String The object will pass through $.param Get serialized string .
  • processData ( By default : true): For non Get request . Whether to automatically data Convert to string .
  • contentType ( By default : “application/x-www-form-urlencoded”): Content encoding type when sending information to the server . ( This can also be done by setting headers). By setting false Skip setting defaults .
  • mimeType ( By default : none): Override the response MIME Type . v1.1+
  • dataType ( By default : none): Expected data type returned by the server (“json”, “jsonp”, “xml”, “html”, or “text”)
  • jsonp ( By default :“callback”): JSONP The name of the callback query parameter
  • jsonpCallback ( By default : “jsonp{N}”): overall situation JSONP Callback function character string ( Or a function returned ) name . Setting this item can enable the browser's cache . v1.1+
  • timeout ( By default : 0): Request timeout in milliseconds , 0 Indicates no timeout .
  • headers: Ajax Additional in the request HTTP Header object
  • async ( By default :true): By default , All requests are asynchronous . If you need to send a synchronization request , Please set this to false.
  • global ( By default :true): The request will trigger a global Ajax Event handler , Set to false The global will not be triggered Ajax event .
  • context ( By default :window): This object is used to set Ajax Context of the relevant callback function (this Point to ).
  • traditional ( By default : false): Activate the traditional way through $.param To get serialized data.
  • cache ( By default : true): Whether browsers should be allowed to cache GET response . from v1.1.4 start , When dataType The options are "script" Or jsonp Time , The default is false.
  • xhrFields ( By default : none): The properties contained in an object are copied verbatim to XMLHttpRequest Examples of . v1.1+
  • username & password ( By default : none): HTTP Basic authentication credentials . v1.1+

If URL It contains =? Or dataType yes “jsonp”, This will be achieved by injecting a <script> Label instead XMLHttpRequest ( see JSONP). here contentType, dataType, headers There are restrictions ,async Not supported .

Ajax Callback function

You can specify the following callback functions , They will perform... In the given order :

  1. beforeSend(xhr, settings): Call before request is issued , It receives xhr Object and settings As a parameter object . If it returns false , The request will be cancelled .

  2. success(data, status, xhr): Call after successful request . Incoming and returned data , And a string containing the success code .

  3. error(xhr, errorType, error): Called when the request has an error . ( overtime , Parsing error , Or the status code is not HTTP 2xx).

  4. complete(xhr, status): Called when the request is complete , Whether the request fails or succeeds .

Promise Callback interface v1.1+

If optional “callbacks” and “deferred” The module is loaded , from $.ajax() Returned XHR Object implements promise Interface chained callback :

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

These methods replace success, error, and complete Callback options .

Ajax event

When global: true Time . stay Ajax Within the request lifecycle , The following events will be triggered .

  1. ajaxStart (global): If nothing else Ajax Requests that are currently active will be triggered .

  2. ajaxBeforeSend (data: xhr, options): Before sending the request , Can be cancelled .

  3. ajaxSend (data: xhr, options): image ajaxBeforeSend, But you can't cancel .

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

  5. ajaxError (data: xhr, options, error): When there are mistakes .

  6. ajaxComplete (data: xhr, options): After the request has been completed , Whether the request is successful or failed .

  7. ajaxStop (global): If this is the last active Ajax request , Will be triggered .

By default ,Ajax Event in document Object . however , If requested context It's a DOM node , This event will be triggered on this node and then DOM Bubbling in . The only exception is ajaxStart & ajaxStop These 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 🐶🔫

Not recommended , use $.ajax replace .

$.ajaxJSONP(options)  ⇒ mock XMLHttpRequest

Execute JSONP Cross domain data acquisition .

This method is relatively $.ajax No advantage , It is not recommended to use .

$.ajaxSettings

A contains Ajax The object of the requested default settings . Most of the settings are in $.ajax Has been described in . It is very useful to set the following as global :

  • timeout ( By default : 0): yes Ajax Request to set a non-zero value to specify a default timeout , In milliseconds .
  • global ( By default : true): Set to false. To prevent triggering Ajax event .
  • xhr ( By default :XMLHttpRequest factory): Set as a function , It returns XMLHttpRequest example ( Or a compatible object )
  • accepts: Requested from the server MIME Type , appoint dataType Worth :
    • 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 a Ajax GET request . This is a $.ajax Abbreviation of .

$.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+

Through Ajax GET Request acquisition JSON data . This is a $.ajax Abbreviation of .

$.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 , stay Ajax The data submitted in the request uses URL Encoded query string representation . If shallow Set to true. Nested objects are not serialized , Nested array values do not use parentheses in their key upper .

If a property value of any object is a function , Instead of a string , This function will be called and will not be serialized until it returns a value .

Besides , Also accept serializeArray Format array , Each of these items has “name” and “value” attribute .

$.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 Ajax POST request . This is a $.ajax Abbreviation of .

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

data The parameter can be a string :

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

load

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

Through GET Ajax Load remote HTML Content code and insert into The current collection in . In addition , One css Selectors can be in url Specified in , like this , You can use matching selector Selector HTML Content to update the collection .

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

If not given CSS selector , The full return text will be used .

Please note that , Without a selector , Any javascript Blocks will execute . If you bring a selector , Match... In selector script Will be deleted .


Form method

serialize

serialize()  ⇒ string

stay Ajax post The request compiles the value of the form element used as the submission into URL Coded character string .

serializeArray

serializeArray()  ⇒ array

Compile the value used as the submitted form element into name and value Object . Form elements that cannot be used ,buttons, Unselected radio buttons/checkboxs Will be skipped . The result does not contain file inputs Your data .

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

submit

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

by "submit" Event binding a handler , Or trigger on the element "submit" event . When there is no given function Parameter is not valid , Trigger the current form “submit” event , And execute the default submit form behavior , Unless you call preventDefault().

When given function Parameter is not valid , On the current element, it is as simple as “submit” Event binding a handler .


Effects

$.fx

Globally animate :

  • $.fx.off ( In support of css transition The default in the browser is false): set up true To ban all animate() transitions.

  • $.fx.speeds: The object used to set the animation time .

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

Change the existing value or add a new attribute to affect the animation of time using a string .

animate

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

Changes the elements in the current object collection css transition Attribute smooth transition .

  • properties: An object , This object contains css Animation values , Or css The name of the frame animation .
  • duration ( By default 400): Time in milliseconds , Or a string .
    • fast (200 ms)
    • slow (600 ms)
    • Any $.fx.speeds Custom properties
  • easing ( By default linear): Specifies the jog type of the animation , Use one of the following :
  • complete: Callback function when the animation is completed
  • li> delay: Excessive delay time in milliseconds v1.1+

Zepto It also supports the following CSS transform attribute :

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

If duration The parameter is 0 Or $.fx.off by true( It does not support css transitions The default in the browser is true), The animation will not be executed ; The target position of the alternative animation effect takes effect immediately . allied , If the specified animation is not completed by animation , And the target position of the animation can take effect . In this case, there is no animation , complete Methods are not called .

If the first argument is a string instead of an object , It will be regarded as a css Keyframe animation CSS keyframe animation The name of .

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

Zepto Use only css Animation of transition effects .jquery of easings Will not support .jquery Relative changes in ("=+10px") syntax Nor does it support . Please check list of animatable properties. Browser support may be different , So be sure to test the browser you want to support .


Touch

Touch events

“touch” Add the following events to the module , You can use on and off.

  • tap — element tap Trigger when .
  • singleTap and doubleTap — This pair of events can be used to detect clicks and double clicks on elements .( If you don't need to check, click 、 double-click , use tap replace ).
  • longTap — When an element is held down for more than 750ms trigger .
  • swipe, swipeLeft, swipeRight, swipeUp, swipeDown — Trigger when an element is crossed .( You can choose a given direction )

These events are also all Zepto Shortcut methods on 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 2013diff

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 2013diff

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 2012diff

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 2011diff

  • 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 2011diff

  • 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 2011diff

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

0.5 01 Mar 2011diff

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

0.4 21 Jan 2011diff

  • 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 2010diff

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

0.2 01 Dec 2010diff

  • 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.