]>
iEval git - gruntmaster-page.git/blob - js/00-zepto.js
1 /* Zepto v1.1.2-15-g59d3fe5 - zepto event ie - zeptojs.com/license */
4 var Zepto = (function() {
5 var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter,
6 document = window.document,
7 elementDisplay = {}, classCache = {},
8 cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
9 fragmentRE = /^\s*<(\w+|!)[^>]*>/,
10 singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
11 tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
12 rootNodeRE = /^(?:body|html)$/i,
13 capitalRE = /([A-Z])/g,
15 // special attributes that should be get/set via method calls
16 methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
18 adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
19 table = document.createElement('table'),
20 tableRow = document.createElement('tr'),
22 'tr': document.createElement('tbody'),
23 'tbody': table, 'thead': table, 'tfoot': table,
24 'td': tableRow, 'th': tableRow,
25 '*': document.createElement('div')
27 readyRE = /complete|loaded|interactive/,
28 classSelectorRE = /^\.([\w-]+)$/,
29 idSelectorRE = /^#([\w-]*)$/,
30 simpleSelectorRE = /^[\w-]*$/,
32 toString = class2type.toString,
35 tempParent = document.createElement('div'),
37 'tabindex': 'tabIndex',
38 'readonly': 'readOnly',
41 'maxlength': 'maxLength',
42 'cellspacing': 'cellSpacing',
43 'cellpadding': 'cellPadding',
47 'frameborder': 'frameBorder',
48 'contenteditable': 'contentEditable'
50 isArray = Array.isArray ||
51 function(object){ return object instanceof Array }
53 zepto.matches = function(element, selector) {
54 if (!selector || !element || element.nodeType !== 1) return false
55 var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
56 element.oMatchesSelector || element.matchesSelector
57 if (matchesSelector) return matchesSelector.call(element, selector)
58 // fall back to performing a selector:
59 var match, parent = element.parentNode, temp = !parent
60 if (temp) (parent = tempParent).appendChild(element)
61 match = ~zepto.qsa(parent, selector).indexOf(element)
62 temp && tempParent.removeChild(element)
67 return obj == null ? String(obj) :
68 class2type[toString.call(obj)] || "object"
71 function isFunction(value) { return type(value) == "function" }
72 function isWindow(obj) { return obj != null && obj == obj.window }
73 function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
74 function isObject(obj) { return type(obj) == "object" }
75 function isPlainObject(obj) {
76 return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
78 function likeArray(obj) { return typeof obj.length == 'number' }
80 function compact(array) { return filter.call(array, function(item){ return item != null }) }
81 function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
82 camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
83 function dasherize(str) {
84 return str.replace(/::/g, '/')
85 .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
86 .replace(/([a-z\d])([A-Z])/g, '$1_$2')
90 uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
92 function classRE(name) {
93 return name in classCache ?
94 classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
97 function maybeAddPx(name, value) {
98 return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
101 function defaultDisplay(nodeName) {
103 if (!elementDisplay[nodeName]) {
104 element = document.createElement(nodeName)
105 document.body.appendChild(element)
106 display = getComputedStyle(element, '').getPropertyValue("display")
107 element.parentNode.removeChild(element)
108 display == "none" && (display = "block")
109 elementDisplay[nodeName] = display
111 return elementDisplay[nodeName]
114 function children(element) {
115 return 'children' in element ?
116 slice.call(element.children) :
117 $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
120 // `$.zepto.fragment` takes a html string and an optional tag name
121 // to generate DOM nodes nodes from the given html string.
122 // The generated DOM nodes are returned as an array.
123 // This function can be overriden in plugins for example to make
124 // it compatible with browsers that don't support the DOM fully.
125 zepto.fragment = function(html, name, properties) {
126 var dom, nodes, container
128 // A special case optimization for a single tag
129 if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
132 if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
133 if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
134 if (!(name in containers)) name = '*'
136 container = containers[name]
137 container.innerHTML = '' + html
138 dom = $.each(slice.call(container.childNodes), function(){
139 container.removeChild(this)
143 if (isPlainObject(properties)) {
145 $.each(properties, function(key, value) {
146 if (methodAttributes.indexOf(key) > -1) nodes[key](value)
147 else nodes.attr(key, value)
154 // `$.zepto.Z` swaps out the prototype of the given `dom` array
155 // of nodes with `$.fn` and thus supplying all the Zepto functions
156 // to the array. Note that `__proto__` is not supported on Internet
157 // Explorer. This method can be overriden in plugins.
158 zepto.Z = function(dom, selector) {
161 dom.selector = selector || ''
165 // `$.zepto.isZ` should return `true` if the given object is a Zepto
166 // collection. This method can be overriden in plugins.
167 zepto.isZ = function(object) {
168 return object instanceof zepto.Z
171 // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
172 // takes a CSS selector and an optional context (and handles various
174 // This method can be overriden in plugins.
175 zepto.init = function(selector, context) {
177 // If nothing given, return an empty Zepto collection
178 if (!selector) return zepto.Z()
179 // Optimize for string selectors
180 else if (typeof selector == 'string') {
181 selector = selector.trim()
182 // If it's a html fragment, create nodes from it
183 // Note: In both Chrome 21 and Firefox 15, DOM error 12
184 // is thrown if the fragment doesn't begin with <
185 if (selector[0] == '<' && fragmentRE.test(selector))
186 dom = zepto.fragment(selector, RegExp.$1, context), selector = null
187 // If there's a context, create a collection on that context first, and select
189 else if (context !== undefined) return $(context).find(selector)
190 // If it's a CSS selector, use it to select nodes.
191 else dom = zepto.qsa(document, selector)
193 // If a function is given, call it when the DOM is ready
194 else if (isFunction(selector)) return $(document).ready(selector)
195 // If a Zepto collection is given, just return it
196 else if (zepto.isZ(selector)) return selector
198 // normalize array if an array of nodes is given
199 if (isArray(selector)) dom = compact(selector)
201 else if (isObject(selector))
202 dom = [selector], selector = null
203 // If it's a html fragment, create nodes from it
204 else if (fragmentRE.test(selector))
205 dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
206 // If there's a context, create a collection on that context first, and select
208 else if (context !== undefined) return $(context).find(selector)
209 // And last but no least, if it's a CSS selector, use it to select nodes.
210 else dom = zepto.qsa(document, selector)
212 // create a new Zepto collection from the nodes found
213 return zepto.Z(dom, selector)
216 // `$` will be the base `Zepto` object. When calling this
217 // function just call `$.zepto.init, which makes the implementation
218 // details of selecting nodes and creating Zepto collections
219 // patchable in plugins.
220 $ = function(selector, context){
221 return zepto.init(selector, context)
224 function extend(target, source, deep) {
226 if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
227 if (isPlainObject(source[key]) && !isPlainObject(target[key]))
229 if (isArray(source[key]) && !isArray(target[key]))
231 extend(target[key], source[key], deep)
233 else if (source[key] !== undefined) target[key] = source[key]
236 // Copy all but undefined properties from one or more
237 // objects to the `target` object.
238 $.extend = function(target){
239 var deep, args = slice.call(arguments, 1)
240 if (typeof target == 'boolean') {
242 target = args.shift()
244 args.forEach(function(arg){ extend(target, arg, deep) })
248 // `$.zepto.qsa` is Zepto's CSS selector implementation which
249 // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
250 // This method can be overriden in plugins.
251 zepto.qsa = function(element, selector){
253 maybeID = selector[0] == '#',
254 maybeClass = !maybeID && selector[0] == '.',
255 nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
256 isSimple = simpleSelectorRE.test(nameOnly)
257 return (isDocument(element) && isSimple && maybeID) ?
258 ( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
259 (element.nodeType !== 1 && element.nodeType !== 9) ? [] :
261 isSimple && !maybeID ?
262 maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
263 element.getElementsByTagName(selector) : // Or a tag
264 element.querySelectorAll(selector) // Or it's not simple, and we need to query all
268 function filtered(nodes, selector) {
269 return selector == null ? $(nodes) : $(nodes).filter(selector)
272 $.contains = function(parent, node) {
273 return parent !== node && parent.contains(node)
276 function funcArg(context, arg, idx, payload) {
277 return isFunction(arg) ? arg.call(context, idx, payload) : arg
280 function setAttribute(node, name, value) {
281 value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
284 // access className property while respecting SVGAnimatedString
285 function className(node, value){
286 var klass = node.className,
287 svg = klass && klass.baseVal !== undefined
289 if (value === undefined) return svg ? klass.baseVal : klass
290 svg ? (klass.baseVal = value) : (node.className = value)
299 // JSON => parse if valid
301 function deserializeValue(value) {
306 ( value == "false" ? false :
307 value == "null" ? null :
308 !/^0/.test(value) && !isNaN(num = Number(value)) ? num :
309 /^[\[\{]/.test(value) ? $.parseJSON(value) :
318 $.isFunction = isFunction
319 $.isWindow = isWindow
321 $.isPlainObject = isPlainObject
323 $.isEmptyObject = function(obj) {
325 for (name in obj) return false
329 $.inArray = function(elem, array, i){
330 return emptyArray.indexOf.call(array, elem, i)
333 $.camelCase = camelize
334 $.trim = function(str) {
335 return str == null ? "" : String.prototype.trim.call(str)
338 // plugin compatibility
343 $.map = function(elements, callback){
344 var value, values = [], i, key
345 if (likeArray(elements))
346 for (i = 0; i < elements.length; i++) {
347 value = callback(elements[i], i)
348 if (value != null) values.push(value)
351 for (key in elements) {
352 value = callback(elements[key], key)
353 if (value != null) values.push(value)
355 return flatten(values)
358 $.each = function(elements, callback){
360 if (likeArray(elements)) {
361 for (i = 0; i < elements.length; i++)
362 if (callback.call(elements[i], i, elements[i]) === false) return elements
364 for (key in elements)
365 if (callback.call(elements[key], key, elements[key]) === false) return elements
371 $.grep = function(elements, callback){
372 return filter.call(elements, callback)
375 if (window.JSON) $.parseJSON = JSON.parse
377 // Populate the class2type map
378 $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
379 class2type[ "[object " + name + "]" ] = name.toLowerCase()
382 // Define methods that will be available on all
385 // Because a collection acts like an array
386 // copy over these useful array functions.
387 forEach: emptyArray.forEach,
388 reduce: emptyArray.reduce,
389 push: emptyArray.push,
390 sort: emptyArray.sort,
391 indexOf: emptyArray.indexOf,
392 concat: emptyArray.concat,
394 // `map` and `slice` in the jQuery API work differently
395 // from their array counterparts
397 return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
400 return $(slice.apply(this, arguments))
403 ready: function(callback){
404 // need to check if document.body exists for IE as that browser reports
405 // document ready when it hasn't yet created the body element
406 if (readyRE.test(document.readyState) && document.body) callback($)
407 else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
411 return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
413 toArray: function(){ return this.get() },
418 return this.each(function(){
419 if (this.parentNode != null)
420 this.parentNode.removeChild(this)
423 each: function(callback){
424 emptyArray.every.call(this, function(el, idx){
425 return callback.call(el, idx, el) !== false
429 filter: function(selector){
430 if (isFunction(selector)) return this.not(this.not(selector))
431 return $(filter.call(this, function(element){
432 return zepto.matches(element, selector)
435 add: function(selector,context){
436 return $(uniq(this.concat($(selector,context))))
438 is: function(selector){
439 return this.length > 0 && zepto.matches(this[0], selector)
441 not: function(selector){
443 if (isFunction(selector) && selector.call !== undefined)
444 this.each(function(idx){
445 if (!selector.call(this,idx)) nodes.push(this)
448 var excludes = typeof selector == 'string' ? this.filter(selector) :
449 (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
450 this.forEach(function(el){
451 if (excludes.indexOf(el) < 0) nodes.push(el)
456 has: function(selector){
457 return this.filter(function(){
458 return isObject(selector) ?
459 $.contains(this, selector) :
460 $(this).find(selector).size()
464 return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
468 return el && !isObject(el) ? el : $(el)
471 var el = this[this.length - 1]
472 return el && !isObject(el) ? el : $(el)
474 find: function(selector){
475 var result, $this = this
476 if (typeof selector == 'object')
477 result = $(selector).filter(function(){
479 return emptyArray.some.call($this, function(parent){
480 return $.contains(parent, node)
483 else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
484 else result = this.map(function(){ return zepto.qsa(this, selector) })
487 closest: function(selector, context){
488 var node = this[0], collection = false
489 if (typeof selector == 'object') collection = $(selector)
490 while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
491 node = node !== context && !isDocument(node) && node.parentNode
494 parents: function(selector){
495 var ancestors = [], nodes = this
496 while (nodes.length > 0)
497 nodes = $.map(nodes, function(node){
498 if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
503 return filtered(ancestors, selector)
505 parent: function(selector){
506 return filtered(uniq(this.pluck('parentNode')), selector)
508 children: function(selector){
509 return filtered(this.map(function(){ return children(this) }), selector)
511 contents: function() {
512 return this.map(function() { return slice.call(this.childNodes) })
514 siblings: function(selector){
515 return filtered(this.map(function(i, el){
516 return filter.call(children(el.parentNode), function(child){ return child!==el })
520 return this.each(function(){ this.innerHTML = '' })
522 // `pluck` is borrowed from Prototype.js
523 pluck: function(property){
524 return $.map(this, function(el){ return el[property] })
527 return this.each(function(){
528 this.style.display == "none" && (this.style.display = '')
529 if (getComputedStyle(this, '').getPropertyValue("display") == "none")
530 this.style.display = defaultDisplay(this.nodeName)
533 replaceWith: function(newContent){
534 return this.before(newContent).remove()
536 wrap: function(structure){
537 var func = isFunction(structure)
538 if (this[0] && !func)
539 var dom = $(structure).get(0),
540 clone = dom.parentNode || this.length > 1
542 return this.each(function(index){
544 func ? structure.call(this, index) :
545 clone ? dom.cloneNode(true) : dom
549 wrapAll: function(structure){
551 $(this[0]).before(structure = $(structure))
553 // drill down to the inmost element
554 while ((children = structure.children()).length) structure = children.first()
555 $(structure).append(this)
559 wrapInner: function(structure){
560 var func = isFunction(structure)
561 return this.each(function(index){
562 var self = $(this), contents = self.contents(),
563 dom = func ? structure.call(this, index) : structure
564 contents.length ? contents.wrapAll(dom) : self.append(dom)
568 this.parent().each(function(){
569 $(this).replaceWith($(this).children())
574 return this.map(function(){ return this.cloneNode(true) })
577 return this.css("display", "none")
579 toggle: function(setting){
580 return this.each(function(){
582 ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
585 prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
586 next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
587 html: function(html){
588 return arguments.length === 0 ?
589 (this.length > 0 ? this[0].innerHTML : null) :
590 this.each(function(idx){
591 var originHtml = this.innerHTML
592 $(this).empty().append( funcArg(this, html, idx, originHtml) )
595 text: function(text){
596 return arguments.length === 0 ?
597 (this.length > 0 ? this[0].textContent : null) :
598 this.each(function(){ this.textContent = (text === undefined) ? '' : ''+text })
600 attr: function(name, value){
602 return (typeof name == 'string' && value === undefined) ?
603 (this.length == 0 || this[0].nodeType !== 1 ? undefined :
604 (name == 'value' && this[0].nodeName == 'INPUT') ? this.val() :
605 (!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result
607 this.each(function(idx){
608 if (this.nodeType !== 1) return
609 if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
610 else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
613 removeAttr: function(name){
614 return this.each(function(){ this.nodeType === 1 && setAttribute(this, name) })
616 prop: function(name, value){
617 name = propMap[name] || name
618 return (value === undefined) ?
619 (this[0] && this[0][name]) :
620 this.each(function(idx){
621 this[name] = funcArg(this, value, idx, this[name])
624 data: function(name, value){
625 var data = this.attr('data-' + name.replace(capitalRE, '-$1').toLowerCase(), value)
626 return data !== null ? deserializeValue(data) : undefined
628 val: function(value){
629 return arguments.length === 0 ?
630 (this[0] && (this[0].multiple ?
631 $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
634 this.each(function(idx){
635 this.value = funcArg(this, value, idx, this.value)
638 offset: function(coordinates){
639 if (coordinates) return this.each(function(index){
641 coords = funcArg(this, coordinates, index, $this.offset()),
642 parentOffset = $this.offsetParent().offset(),
644 top: coords.top - parentOffset.top,
645 left: coords.left - parentOffset.left
648 if ($this.css('position') == 'static') props['position'] = 'relative'
651 if (this.length==0) return null
652 var obj = this[0].getBoundingClientRect()
654 left: obj.left + window.pageXOffset,
655 top: obj.top + window.pageYOffset,
656 width: Math.round(obj.width),
657 height: Math.round(obj.height)
660 css: function(property, value){
661 if (arguments.length < 2) {
662 var element = this[0], computedStyle = getComputedStyle(element, '')
664 if (typeof property == 'string')
665 return element.style[camelize(property)] || computedStyle.getPropertyValue(property)
666 else if (isArray(property)) {
668 $.each(isArray(property) ? property: [property], function(_, prop){
669 props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
676 if (type(property) == 'string') {
677 if (!value && value !== 0)
678 this.each(function(){ this.style.removeProperty(dasherize(property)) })
680 css = dasherize(property) + ":" + maybeAddPx(property, value)
682 for (key in property)
683 if (!property[key] && property[key] !== 0)
684 this.each(function(){ this.style.removeProperty(dasherize(key)) })
686 css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
689 return this.each(function(){ this.style.cssText += ';' + css })
691 index: function(element){
692 return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
694 hasClass: function(name){
695 if (!name) return false
696 return emptyArray.some.call(this, function(el){
697 return this.test(className(el))
700 addClass: function(name){
701 if (!name) return this
702 return this.each(function(idx){
704 var cls = className(this), newName = funcArg(this, name, idx, cls)
705 newName.split(/\s+/g).forEach(function(klass){
706 if (!$(this).hasClass(klass)) classList.push(klass)
708 classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
711 removeClass: function(name){
712 return this.each(function(idx){
713 if (name === undefined) return className(this, '')
714 classList = className(this)
715 funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
716 classList = classList.replace(classRE(klass), " ")
718 className(this, classList.trim())
721 toggleClass: function(name, when){
722 if (!name) return this
723 return this.each(function(idx){
724 var $this = $(this), names = funcArg(this, name, idx, className(this))
725 names.split(/\s+/g).forEach(function(klass){
726 (when === undefined ? !$this.hasClass(klass) : when) ?
727 $this.addClass(klass) : $this.removeClass(klass)
731 scrollTop: function(value){
732 if (!this.length) return
733 var hasScrollTop = 'scrollTop' in this[0]
734 if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
735 return this.each(hasScrollTop ?
736 function(){ this.scrollTop = value } :
737 function(){ this.scrollTo(this.scrollX, value) })
739 scrollLeft: function(value){
740 if (!this.length) return
741 var hasScrollLeft = 'scrollLeft' in this[0]
742 if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset
743 return this.each(hasScrollLeft ?
744 function(){ this.scrollLeft = value } :
745 function(){ this.scrollTo(value, this.scrollY) })
747 position: function() {
748 if (!this.length) return
751 // Get *real* offsetParent
752 offsetParent = this.offsetParent(),
753 // Get correct offsets
754 offset = this.offset(),
755 parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset()
757 // Subtract element margins
758 // note: when an element has margin: auto the offsetLeft and marginLeft
759 // are the same in Safari causing offset.left to incorrectly be 0
760 offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
761 offset.left -= parseFloat( $(elem).css('margin-left') ) || 0
763 // Add offsetParent borders
764 parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0
765 parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0
767 // Subtract the two offsets
769 top: offset.top - parentOffset.top,
770 left: offset.left - parentOffset.left
773 offsetParent: function() {
774 return this.map(function(){
775 var parent = this.offsetParent || document.body
776 while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
777 parent = parent.offsetParent
784 $.fn.detach = $.fn.remove
786 // Generate the `width` and `height` functions
787 ;['width', 'height'].forEach(function(dimension){
788 var dimensionProperty =
789 dimension.replace(/./, function(m){ return m[0].toUpperCase() })
791 $.fn[dimension] = function(value){
792 var offset, el = this[0]
793 if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
794 isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
795 (offset = this.offset()) && offset[dimension]
796 else return this.each(function(idx){
798 el.css(dimension, funcArg(this, value, idx, el[dimension]()))
803 function traverseNode(node, fun) {
805 for (var key in node.childNodes) traverseNode(node.childNodes[key], fun)
808 // Generate the `after`, `prepend`, `before`, `append`,
809 // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
810 adjacencyOperators.forEach(function(operator, operatorIndex) {
811 var inside = operatorIndex % 2 //=> prepend, append
813 $.fn[operator] = function(){
814 // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
815 var argType, nodes = $.map(arguments, function(arg) {
817 return argType == "object" || argType == "array" || arg == null ?
818 arg : zepto.fragment(arg)
820 parent, copyByClone = this.length > 1
821 if (nodes.length < 1) return this
823 return this.each(function(_, target){
824 parent = inside ? target : target.parentNode
826 // convert all methods to a "before" operation
827 target = operatorIndex == 0 ? target.nextSibling :
828 operatorIndex == 1 ? target.firstChild :
829 operatorIndex == 2 ? target :
832 nodes.forEach(function(node){
833 if (copyByClone) node = node.cloneNode(true)
834 else if (!parent) return $(node).remove()
836 traverseNode(parent.insertBefore(node, target), function(el){
837 if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
838 (!el.type || el.type === 'text/javascript') && !el.src)
839 window['eval'].call(window, el.innerHTML)
845 // after => insertAfter
846 // prepend => prependTo
847 // before => insertBefore
848 // append => appendTo
849 $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
850 $(html)[operator](this)
855 zepto.Z.prototype = $.fn
857 // Export internal API functions in the `$.zepto` namespace
859 zepto.deserializeValue = deserializeValue
866 window.$ === undefined && (window.$ = Zepto)
869 var $$ = $.zepto.qsa, _zid = 1, undefined,
870 slice = Array.prototype.slice,
871 isFunction = $.isFunction,
872 isString = function(obj){ return typeof obj == 'string' },
875 focusinSupported = 'onfocusin' in window,
876 focus = { focus: 'focusin', blur: 'focusout' },
877 hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }
879 specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'
881 function zid(element) {
882 return element._zid || (element._zid = _zid++)
884 function findHandlers(element, event, fn, selector) {
886 if (event.ns) var matcher = matcherFor(event.ns)
887 return (handlers[zid(element)] || []).filter(function(handler) {
889 && (!event.e || handler.e == event.e)
890 && (!event.ns || matcher.test(handler.ns))
891 && (!fn || zid(handler.fn) === zid(fn))
892 && (!selector || handler.sel == selector)
895 function parse(event) {
896 var parts = ('' + event).split('.')
897 return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
899 function matcherFor(ns) {
900 return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
903 function eventCapture(handler, captureSetting) {
904 return handler.del &&
905 (!focusinSupported && (handler.e in focus)) ||
909 function realEvent(type) {
910 return hover[type] || (focusinSupported && focus[type]) || type
913 function add(element, events, fn, data, selector, delegator, capture){
914 var id = zid(element), set = (handlers[id] || (handlers[id] = []))
915 events.split(/\s/).forEach(function(event){
916 if (event == 'ready') return $(document).ready(fn)
917 var handler = parse(event)
919 handler.sel = selector
920 // emulate mouseenter, mouseleave
921 if (handler.e in hover) fn = function(e){
922 var related = e.relatedTarget
923 if (!related || (related !== this && !$.contains(this, related)))
924 return handler.fn.apply(this, arguments)
926 handler.del = delegator
927 var callback = delegator || fn
928 handler.proxy = function(e){
930 if (e.isImmediatePropagationStopped()) return
932 var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args))
933 if (result === false) e.preventDefault(), e.stopPropagation()
936 handler.i = set.length
938 if ('addEventListener' in element)
939 element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
942 function remove(element, events, fn, selector, capture){
943 var id = zid(element)
944 ;(events || '').split(/\s/).forEach(function(event){
945 findHandlers(element, event, fn, selector).forEach(function(handler){
946 delete handlers[id][handler.i]
947 if ('removeEventListener' in element)
948 element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
953 $.event = { add: add, remove: remove }
955 $.proxy = function(fn, context) {
956 if (isFunction(fn)) {
957 var proxyFn = function(){ return fn.apply(context, arguments) }
958 proxyFn._zid = zid(fn)
960 } else if (isString(context)) {
961 return $.proxy(fn[context], fn)
963 throw new TypeError("expected function")
967 $.fn.bind = function(event, data, callback){
968 return this.on(event, data, callback)
970 $.fn.unbind = function(event, callback){
971 return this.off(event, callback)
973 $.fn.one = function(event, selector, data, callback){
974 return this.on(event, selector, data, callback, 1)
977 var returnTrue = function(){return true},
978 returnFalse = function(){return false},
979 ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/,
981 preventDefault: 'isDefaultPrevented',
982 stopImmediatePropagation: 'isImmediatePropagationStopped',
983 stopPropagation: 'isPropagationStopped'
986 function compatible(event, source) {
987 if (source || !event.isDefaultPrevented) {
988 source || (source = event)
990 $.each(eventMethods, function(name, predicate) {
991 var sourceMethod = source[name]
992 event[name] = function(){
993 this[predicate] = returnTrue
994 return sourceMethod && sourceMethod.apply(source, arguments)
996 event[predicate] = returnFalse
999 if (source.defaultPrevented !== undefined ? source.defaultPrevented :
1000 'returnValue' in source ? source.returnValue === false :
1001 source.getPreventDefault && source.getPreventDefault())
1002 event.isDefaultPrevented = returnTrue
1007 function createProxy(event) {
1008 var key, proxy = { originalEvent: event }
1010 if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key]
1012 return compatible(proxy, event)
1015 $.fn.delegate = function(selector, event, callback){
1016 return this.on(event, selector, callback)
1018 $.fn.undelegate = function(selector, event, callback){
1019 return this.off(event, selector, callback)
1022 $.fn.live = function(event, callback){
1023 $(document.body).delegate(this.selector, event, callback)
1026 $.fn.die = function(event, callback){
1027 $(document.body).undelegate(this.selector, event, callback)
1031 $.fn.on = function(event, selector, data, callback, one){
1032 var autoRemove, delegator, $this = this
1033 if (event && !isString(event)) {
1034 $.each(event, function(type, fn){
1035 $this.on(type, selector, data, fn, one)
1040 if (!isString(selector) && !isFunction(callback) && callback !== false)
1041 callback = data, data = selector, selector = undefined
1042 if (isFunction(data) || data === false)
1043 callback = data, data = undefined
1045 if (callback === false) callback = returnFalse
1047 return $this.each(function(_, element){
1048 if (one) autoRemove = function(e){
1049 remove(element, e.type, callback)
1050 return callback.apply(this, arguments)
1053 if (selector) delegator = function(e){
1054 var evt, match = $(e.target).closest(selector, element).get(0)
1055 if (match && match !== element) {
1056 evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
1057 return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
1061 add(element, event, callback, data, selector, delegator || autoRemove)
1064 $.fn.off = function(event, selector, callback){
1066 if (event && !isString(event)) {
1067 $.each(event, function(type, fn){
1068 $this.off(type, selector, fn)
1073 if (!isString(selector) && !isFunction(callback) && callback !== false)
1074 callback = selector, selector = undefined
1076 if (callback === false) callback = returnFalse
1078 return $this.each(function(){
1079 remove(this, event, callback, selector)
1083 $.fn.trigger = function(event, args){
1084 event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event)
1086 return this.each(function(){
1087 // items in the collection might not be DOM elements
1088 if('dispatchEvent' in this) this.dispatchEvent(event)
1089 else $(this).triggerHandler(event, args)
1093 // triggers event handlers on current element just as if an event occurred,
1094 // doesn't trigger an actual event, doesn't bubble
1095 $.fn.triggerHandler = function(event, args){
1097 this.each(function(i, element){
1098 e = createProxy(isString(event) ? $.Event(event) : event)
1101 $.each(findHandlers(element, event.type || event), function(i, handler){
1102 result = handler.proxy(e)
1103 if (e.isImmediatePropagationStopped()) return false
1109 // shortcut methods for `.bind(event, fn)` for each event type
1110 ;('focusin focusout load resize scroll unload click dblclick '+
1111 'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+
1112 'change select keydown keypress keyup error').split(' ').forEach(function(event) {
1113 $.fn[event] = function(callback) {
1115 this.bind(event, callback) :
1120 ;['focus', 'blur'].forEach(function(name) {
1121 $.fn[name] = function(callback) {
1122 if (callback) this.bind(name, callback)
1123 else this.each(function(){
1124 try { this[name]() }
1131 $.Event = function(type, props) {
1132 if (!isString(type)) props = type, type = props.type
1133 var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
1134 if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
1135 event.initEvent(type, bubbles, true)
1136 return compatible(event)
1142 // __proto__ doesn't exist on IE<11, so redefine
1143 // the Z function to use object extension instead
1144 if (!('__proto__' in {})) {
1146 Z: function(dom, selector){
1149 dom.selector = selector || ''
1153 // this is a kludge but works
1154 isZ: function(object){
1155 return $.type(object) === 'array' && '__Z' in object
1160 // getComputedStyle shouldn't freak out when called
1161 // without a valid element as argument
1163 getComputedStyle(undefined)
1165 var nativeGetComputedStyle = getComputedStyle;
1166 window.getComputedStyle = function(element){
1168 return nativeGetComputedStyle(element)
This page took 0.179212 seconds and 4 git commands to generate.