Adding github repo

This commit is contained in:
2015-04-18 07:42:16 +03:00
parent 7f2f7fe494
commit d9a8e0979d
222 changed files with 0 additions and 47242 deletions

File diff suppressed because one or more lines are too long

View File

@@ -1,761 +0,0 @@
/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @version 0.6.9
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
/*jslint browser:true, node:true*/
/*global define, Event, Node*/
/**
* Instantiate fast-clicking listeners on the specificed layer.
*
* @constructor
* @param {Element} layer The layer to listen on
*/
function FastClick(layer) {
'use strict';
var oldOnClick, self = this;
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
if (!layer || !layer.nodeType) {
throw new TypeError('Layer must be a document node');
}
/** @type function() */
this.onClick = function() { return FastClick.prototype.onClick.apply(self, arguments); };
/** @type function() */
this.onMouse = function() { return FastClick.prototype.onMouse.apply(self, arguments); };
/** @type function() */
this.onTouchStart = function() { return FastClick.prototype.onTouchStart.apply(self, arguments); };
/** @type function() */
this.onTouchMove = function() { return FastClick.prototype.onTouchMove.apply(self, arguments); };
/** @type function() */
this.onTouchEnd = function() { return FastClick.prototype.onTouchEnd.apply(self, arguments); };
/** @type function() */
this.onTouchCancel = function() { return FastClick.prototype.onTouchCancel.apply(self, arguments); };
if (FastClick.notNeeded(layer)) {
return;
}
// Set up event handlers as required
if (this.deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
/**
* Android requires exceptions.
*
* @type boolean
*/
FastClick.prototype.deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
/**
* iOS requires exceptions.
*
* @type boolean
*/
FastClick.prototype.deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
FastClick.prototype.deviceIsIOS4 = FastClick.prototype.deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0(+?) requires the target element to be manually derived
*
* @type boolean
*/
FastClick.prototype.deviceIsIOSWithBadTarget = FastClick.prototype.deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((this.deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'video':
return true;
}
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
case 'textarea':
case 'select':
return true;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
'use strict';
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent('click', true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
'use strict';
var length;
if (this.deviceIsIOS && targetElement.setSelectionRange) {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
'use strict';
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
'use strict';
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
'use strict';
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (this.deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!this.deviceIsIOS4) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
if (touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < 200) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
'use strict';
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Update the last position.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchMove = function(event) {
'use strict';
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
'use strict';
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
'use strict';
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < 200) {
this.cancelNextClick = true;
return true;
}
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (this.deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (this.deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (this.deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
if (!this.deviceIsIOS4 || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (this.deviceIsIOS && !this.deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
'use strict';
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
'use strict';
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
'use strict';
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
'use strict';
var layer = this.layer;
if (this.deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchmove', this.onTouchMove, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
'use strict';
var metaViewport;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
if ((/Chrome\/[0-9]+/).test(navigator.userAgent)) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (FastClick.prototype.deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport && metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
*/
FastClick.attach = function(layer) {
'use strict';
return new FastClick(layer);
};
if (typeof define !== 'undefined' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
'use strict';
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}

View File

@@ -1,645 +0,0 @@
/**
* Ajax Autocomplete for jQuery, version 1.2.7
* (c) 2013 Tomas Kirda
*
* Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.
* For details, see the web site: http://www.devbridge.com/projects/autocomplete/jquery/
*
*/
/*jslint browser: true, white: true, plusplus: true */
/*global define, window, document, jQuery */
// Expose plugin as an AMD module if AMD loader is present:
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
'use strict';
var
utils = (function () {
return {
extend: function (target, source) {
return $.extend(target, source);
},
createNode: function (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.firstChild;
}
};
}()),
keys = {
ESC: 27,
TAB: 9,
RETURN: 13,
UP: 38,
DOWN: 40
};
function Autocomplete(el, options) {
var noop = function () { },
that = this,
defaults = {
autoSelectFirst: false,
appendTo: 'body',
serviceUrl: null,
lookup: null,
onSelect: null,
width: 'auto',
minChars: 1,
maxHeight: 300,
deferRequestBy: 0,
params: {},
formatResult: Autocomplete.formatResult,
delimiter: null,
zIndex: 9999,
type: 'GET',
noCache: false,
onSearchStart: noop,
onSearchComplete: noop,
containerClass: 'autocomplete-suggestions',
tabDisabled: false,
dataType: 'text',
lookupFilter: function (suggestion, originalQuery, queryLowerCase) {
return suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;
},
paramName: 'query',
transformResult: function (response) {
return typeof response === 'string' ? $.parseJSON(response) : response;
}
};
// Shared variables:
that.element = el;
that.el = $(el);
that.suggestions = [];
that.badQueries = [];
that.selectedIndex = -1;
that.currentValue = that.element.value;
that.intervalId = 0;
that.cachedResponse = [];
that.onChangeInterval = null;
that.onChange = null;
that.ignoreValueChange = false;
that.isLocal = false;
that.suggestionsContainer = null;
that.options = $.extend({}, defaults, options);
that.classes = {
selected: 'autocomplete-selected',
suggestion: 'autocomplete-suggestion'
};
// Initialize and set options:
that.initialize();
that.setOptions(options);
}
Autocomplete.utils = utils;
$.Autocomplete = Autocomplete;
Autocomplete.formatResult = function (suggestion, currentValue) {
var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g'),
pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
return suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>');
};
Autocomplete.prototype = {
killerFn: null,
initialize: function () {
var that = this,
suggestionSelector = '.' + that.classes.suggestion,
selected = that.classes.selected,
options = that.options,
container;
// Remove autocomplete attribute to prevent native suggestions:
that.element.setAttribute('autocomplete', 'off');
that.killerFn = function (e) {
if ($(e.target).closest('.' + that.options.containerClass).length === 0) {
that.killSuggestions();
that.disableKillerFn();
}
};
// Determine suggestions width:
if (!options.width || options.width === 'auto') {
options.width = that.el.outerWidth();
}
that.suggestionsContainer = Autocomplete.utils.createNode('<div class="' + options.containerClass + '" style="position: absolute; display: none;"></div>');
container = $(that.suggestionsContainer);
container.appendTo(options.appendTo).width(options.width);
// Listen for mouse over event on suggestions list:
container.on('mouseover.autocomplete', suggestionSelector, function () {
that.activate($(this).data('index'));
});
// Deselect active element when mouse leaves suggestions container:
container.on('mouseout.autocomplete', function () {
that.selectedIndex = -1;
container.children('.' + selected).removeClass(selected);
});
// Listen for click event on suggestions list:
container.on('click.autocomplete', suggestionSelector, function () {
that.select($(this).data('index'), false);
});
that.fixPosition();
// Opera does not like keydown:
if (window.opera) {
that.el.on('keypress.autocomplete', function (e) { that.onKeyPress(e); });
} else {
that.el.on('keydown.autocomplete', function (e) { that.onKeyPress(e); });
}
that.el.on('keyup.autocomplete', function (e) { that.onKeyUp(e); });
that.el.on('blur.autocomplete', function () { that.onBlur(); });
that.el.on('focus.autocomplete', function () { that.fixPosition(); });
},
onBlur: function () {
this.enableKillerFn();
},
setOptions: function (suppliedOptions) {
var that = this,
options = that.options;
utils.extend(options, suppliedOptions);
that.isLocal = $.isArray(options.lookup);
if (that.isLocal) {
options.lookup = that.verifySuggestionsFormat(options.lookup);
}
// Adjust height, width and z-index:
$(that.suggestionsContainer).css({
'max-height': options.maxHeight + 'px',
'width': options.width + 'px',
'z-index': options.zIndex
});
},
clearCache: function () {
this.cachedResponse = [];
this.badQueries = [];
},
clear: function () {
this.clearCache();
this.currentValue = null;
this.suggestions = [];
},
disable: function () {
this.disabled = true;
},
enable: function () {
this.disabled = false;
},
fixPosition: function () {
var that = this,
offset;
// Don't adjsut position if custom container has been specified:
if (that.options.appendTo !== 'body') {
return;
}
offset = that.el.offset();
$(that.suggestionsContainer).css({
top: (offset.top + that.el.outerHeight()) + 'px',
left: offset.left + 'px'
});
},
enableKillerFn: function () {
var that = this;
$(document).on('click.autocomplete', that.killerFn);
},
disableKillerFn: function () {
var that = this;
$(document).off('click.autocomplete', that.killerFn);
},
killSuggestions: function () {
var that = this;
that.stopKillSuggestions();
that.intervalId = window.setInterval(function () {
that.hide();
that.stopKillSuggestions();
}, 300);
},
stopKillSuggestions: function () {
window.clearInterval(this.intervalId);
},
onKeyPress: function (e) {
var that = this;
// If suggestions are hidden and user presses arrow down, display suggestions:
if (!that.disabled && !that.visible && e.keyCode === keys.DOWN && that.currentValue) {
that.suggest();
return;
}
if (that.disabled || !that.visible) {
return;
}
switch (e.keyCode) {
case keys.ESC:
that.el.val(that.currentValue);
that.hide();
break;
case keys.TAB:
case keys.RETURN:
if (that.selectedIndex === -1) {
that.hide();
return;
}
that.select(that.selectedIndex, e.keyCode === keys.RETURN);
if (e.keyCode === keys.TAB && this.options.tabDisabled === false) {
return;
}
break;
case keys.UP:
that.moveUp();
break;
case keys.DOWN:
that.moveDown();
break;
default:
return;
}
// Cancel event if function did not return:
e.stopImmediatePropagation();
e.preventDefault();
},
onKeyUp: function (e) {
var that = this;
if (that.disabled) {
return;
}
switch (e.keyCode) {
case keys.UP:
case keys.DOWN:
return;
}
clearInterval(that.onChangeInterval);
if (that.currentValue !== that.el.val()) {
if (that.options.deferRequestBy > 0) {
// Defer lookup in case when value changes very quickly:
that.onChangeInterval = setInterval(function () {
that.onValueChange();
}, that.options.deferRequestBy);
} else {
that.onValueChange();
}
}
},
onValueChange: function () {
var that = this,
q;
clearInterval(that.onChangeInterval);
that.currentValue = that.element.value;
q = that.getQuery(that.currentValue);
that.selectedIndex = -1;
if (that.ignoreValueChange) {
that.ignoreValueChange = false;
return;
}
if (q.length < that.options.minChars) {
that.hide();
} else {
that.getSuggestions(q);
}
},
getQuery: function (value) {
var delimiter = this.options.delimiter,
parts;
if (!delimiter) {
return $.trim(value);
}
parts = value.split(delimiter);
return $.trim(parts[parts.length - 1]);
},
getSuggestionsLocal: function (query) {
var that = this,
queryLowerCase = query.toLowerCase(),
filter = that.options.lookupFilter;
return {
suggestions: $.grep(that.options.lookup, function (suggestion) {
return filter(suggestion, query, queryLowerCase);
})
};
},
getSuggestions: function (q) {
var response,
that = this,
options = that.options,
serviceUrl = options.serviceUrl;
response = that.isLocal ? that.getSuggestionsLocal(q) : that.cachedResponse[q];
if (response && $.isArray(response.suggestions)) {
that.suggestions = response.suggestions;
that.suggest();
} else if (!that.isBadQuery(q)) {
options.params[options.paramName] = q;
if (options.onSearchStart.call(that.element, options.params) === false) {
return;
}
if ($.isFunction(options.serviceUrl)) {
serviceUrl = options.serviceUrl.call(that.element, q);
}
$.ajax({
url: serviceUrl,
data: options.ignoreParams ? null : options.params,
type: options.type,
dataType: options.dataType
}).done(function (data) {
that.processResponse(data, q);
options.onSearchComplete.call(that.element, q);
});
}
},
isBadQuery: function (q) {
var badQueries = this.badQueries,
i = badQueries.length;
while (i--) {
if (q.indexOf(badQueries[i]) === 0) {
return true;
}
}
return false;
},
hide: function () {
var that = this;
that.visible = false;
that.selectedIndex = -1;
$(that.suggestionsContainer).hide();
},
suggest: function () {
if (this.suggestions.length === 0) {
this.hide();
return;
}
var that = this,
formatResult = that.options.formatResult,
value = that.getQuery(that.currentValue),
className = that.classes.suggestion,
classSelected = that.classes.selected,
container = $(that.suggestionsContainer),
html = '';
// Build suggestions inner HTML:
$.each(that.suggestions, function (i, suggestion) {
html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value) + '</div>';
});
container.html(html).show();
that.visible = true;
// Select first value by default:
if (that.options.autoSelectFirst) {
that.selectedIndex = 0;
container.children().first().addClass(classSelected);
}
},
verifySuggestionsFormat: function (suggestions) {
// If suggestions is string array, convert them to supported format:
if (suggestions.length && typeof suggestions[0] === 'string') {
return $.map(suggestions, function (value) {
return { value: value, data: null };
});
}
return suggestions;
},
processResponse: function (response, originalQuery) {
var that = this,
options = that.options,
result = options.transformResult(response, originalQuery);
result.suggestions = that.verifySuggestionsFormat(result.suggestions);
// Cache results if cache is not disabled:
if (!options.noCache) {
that.cachedResponse[result[options.paramName]] = result;
if (result.suggestions.length === 0) {
that.badQueries.push(result[options.paramName]);
}
}
// Display suggestions only if returned query matches current value:
if (originalQuery === that.getQuery(that.currentValue)) {
that.suggestions = result.suggestions;
that.suggest();
}
},
activate: function (index) {
var that = this,
activeItem,
selected = that.classes.selected,
container = $(that.suggestionsContainer),
children = container.children();
container.children('.' + selected).removeClass(selected);
that.selectedIndex = index;
if (that.selectedIndex !== -1 && children.length > that.selectedIndex) {
activeItem = children.get(that.selectedIndex);
$(activeItem).addClass(selected);
return activeItem;
}
return null;
},
select: function (i, shouldIgnoreNextValueChange) {
var that = this,
selectedValue = that.suggestions[i];
if (selectedValue) {
that.el.val(selectedValue);
that.ignoreValueChange = shouldIgnoreNextValueChange;
that.hide();
that.onSelect(i);
}
},
moveUp: function () {
var that = this;
if (that.selectedIndex === -1) {
return;
}
if (that.selectedIndex === 0) {
$(that.suggestionsContainer).children().first().removeClass(that.classes.selected);
that.selectedIndex = -1;
that.el.val(that.currentValue);
return;
}
that.adjustScroll(that.selectedIndex - 1);
},
moveDown: function () {
var that = this;
if (that.selectedIndex === (that.suggestions.length - 1)) {
return;
}
that.adjustScroll(that.selectedIndex + 1);
},
adjustScroll: function (index) {
var that = this,
activeItem = that.activate(index),
offsetTop,
upperBound,
lowerBound,
heightDelta = 25;
if (!activeItem) {
return;
}
offsetTop = activeItem.offsetTop;
upperBound = $(that.suggestionsContainer).scrollTop();
lowerBound = upperBound + that.options.maxHeight - heightDelta;
if (offsetTop < upperBound) {
$(that.suggestionsContainer).scrollTop(offsetTop);
} else if (offsetTop > lowerBound) {
$(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta);
}
that.el.val(that.getValue(that.suggestions[index].value));
},
onSelect: function (index) {
var that = this,
onSelectCallback = that.options.onSelect,
suggestion = that.suggestions[index];
that.el.val(that.getValue(suggestion.value));
if ($.isFunction(onSelectCallback)) {
onSelectCallback.call(that.element, suggestion);
}
},
getValue: function (value) {
var that = this,
delimiter = that.options.delimiter,
currentValue,
parts;
if (!delimiter) {
return value;
}
currentValue = that.currentValue;
parts = currentValue.split(delimiter);
if (parts.length === 1) {
return value;
}
return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
},
dispose: function () {
var that = this;
that.el.off('.autocomplete').removeData('autocomplete');
that.disableKillerFn();
$(that.suggestionsContainer).remove();
}
};
// Create chainable jQuery plugin:
$.fn.autocomplete = function (options, args) {
var dataKey = 'autocomplete';
// If function invoked without argument return
// instance of the first matched element:
if (arguments.length === 0) {
return this.first().data(dataKey);
}
return this.each(function () {
var inputElement = $(this),
instance = inputElement.data(dataKey);
if (typeof options === 'string') {
if (instance && typeof instance[options] === 'function') {
instance[options](args);
}
} else {
// If instance already exists, destroy it:
if (instance && instance.dispose) {
instance.dispose();
}
instance = new Autocomplete(this, options);
inputElement.data(dataKey, instance);
}
});
};
}));

View File

@@ -1,107 +0,0 @@
/*!
* jQuery Cookie Plugin v1.3.1
* https://github.com/carhartl/jquery-cookie
*
* Copyright 2013 Klaus Hartl
* Released under the MIT license
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) {
var pluses = /\+/g;
function decode(s) {
if (config.raw) {
return s;
}
try {
// If we can't decode the cookie, ignore it, it's unusable.
return decodeURIComponent(s.replace(pluses, ' '));
} catch(e) {}
}
function decodeAndParse(s) {
if (s.indexOf('"') === 0) {
// This is a quoted cookie as according to RFC2068, unescape...
s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
s = decode(s);
try {
// If we can't parse the cookie, ignore it, it's unusable.
return config.json ? JSON.parse(s) : s;
} catch(e) {}
}
var config = $.cookie = function (key, value, options) {
// Write
if (value !== undefined) {
options = $.extend({}, config.defaults, options);
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
value = config.json ? JSON.stringify(value) : String(value);
return (document.cookie = [
config.raw ? key : encodeURIComponent(key),
'=',
config.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// Read
var result = key ? undefined : {};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all. Also prevents odd result when
// calling $.cookie().
var cookies = document.cookie ? document.cookie.split('; ') : [];
for (var i = 0, l = cookies.length; i < l; i++) {
var parts = cookies[i].split('=');
var name = decode(parts.shift());
var cookie = parts.join('=');
if (key && key === name) {
result = decodeAndParse(cookie);
break;
}
// Prevent storing a cookie that we couldn't decode.
if (!key && (cookie = decodeAndParse(cookie)) !== undefined) {
result[name] = cookie;
}
}
return result;
};
config.defaults = {};
$.removeCookie = function (key, options) {
if ($.cookie(key) !== undefined) {
// Must not alter options, thus extending a fresh object...
$.cookie(key, '', $.extend({}, options, { expires: -1 }));
return true;
}
return false;
};
}));

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -1,426 +0,0 @@
/*
* The MIT License
*
* Copyright (c) 2012 James Allardice
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
// Defines the global Placeholders object along with various utility methods
(function (global) {
"use strict";
// Cross-browser DOM event binding
function addEventListener(elem, event, fn) {
if (elem.addEventListener) {
return elem.addEventListener(event, fn, false);
}
if (elem.attachEvent) {
return elem.attachEvent("on" + event, fn);
}
}
// Check whether an item is in an array (we don't use Array.prototype.indexOf so we don't clobber any existing polyfills - this is a really simple alternative)
function inArray(arr, item) {
var i, len;
for (i = 0, len = arr.length; i < len; i++) {
if (arr[i] === item) {
return true;
}
}
return false;
}
// Move the caret to the index position specified. Assumes that the element has focus
function moveCaret(elem, index) {
var range;
if (elem.createTextRange) {
range = elem.createTextRange();
range.move("character", index);
range.select();
} else if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(index, index);
}
}
// Attempt to change the type property of an input element
function changeType(elem, type) {
try {
elem.type = type;
return true;
} catch (e) {
// You can't change input type in IE8 and below
return false;
}
}
// Expose public methods
global.Placeholders = {
Utils: {
addEventListener: addEventListener,
inArray: inArray,
moveCaret: moveCaret,
changeType: changeType
}
};
}(this));
(function (global) {
"use strict";
var validTypes = [
"text",
"search",
"url",
"tel",
"email",
"password",
"number",
"textarea"
],
// The list of keycodes that are not allowed when the polyfill is configured to hide-on-input
badKeys = [
// The following keys all cause the caret to jump to the end of the input value
27, // Escape
33, // Page up
34, // Page down
35, // End
36, // Home
// Arrow keys allow you to move the caret manually, which should be prevented when the placeholder is visible
37, // Left
38, // Up
39, // Right
40, // Down
// The following keys allow you to modify the placeholder text by removing characters, which should be prevented when the placeholder is visible
8, // Backspace
46 // Delete
],
// Styling variables
placeholderStyleColor = "#ccc",
placeholderClassName = "placeholdersjs",
classNameRegExp = new RegExp("(?:^|\\s)" + placeholderClassName + "(?!\\S)"),
// These will hold references to all elements that can be affected. NodeList objects are live, so we only need to get those references once
inputs, textareas,
// The various data-* attributes used by the polyfill
ATTR_CURRENT_VAL = "data-placeholder-value",
ATTR_ACTIVE = "data-placeholder-active",
ATTR_INPUT_TYPE = "data-placeholder-type",
ATTR_FORM_HANDLED = "data-placeholder-submit",
ATTR_EVENTS_BOUND = "data-placeholder-bound",
ATTR_OPTION_FOCUS = "data-placeholder-focus",
ATTR_OPTION_LIVE = "data-placeholder-live",
// Various other variables used throughout the rest of the script
test = document.createElement("input"),
head = document.getElementsByTagName("head")[0],
root = document.documentElement,
Placeholders = global.Placeholders,
Utils = Placeholders.Utils,
hideOnInput, liveUpdates, keydownVal, styleElem, styleRules, placeholder, timer, form, elem, len, i;
// No-op (used in place of public methods when native support is detected)
function noop() {}
// Hide the placeholder value on a single element. Returns true if the placeholder was hidden and false if it was not (because it wasn't visible in the first place)
function hidePlaceholder(elem) {
var type;
if (elem.value === elem.getAttribute(ATTR_CURRENT_VAL) && elem.getAttribute(ATTR_ACTIVE) === "true") {
elem.setAttribute(ATTR_ACTIVE, "false");
elem.value = "";
elem.className = elem.className.replace(classNameRegExp, "");
// If the polyfill has changed the type of the element we need to change it back
type = elem.getAttribute(ATTR_INPUT_TYPE);
if (type) {
elem.type = type;
}
return true;
}
return false;
}
// Show the placeholder value on a single element. Returns true if the placeholder was shown and false if it was not (because it was already visible)
function showPlaceholder(elem) {
var type,
val = elem.getAttribute(ATTR_CURRENT_VAL);
if (elem.value === "" && val) {
elem.setAttribute(ATTR_ACTIVE, "true");
elem.value = val;
elem.className += " " + placeholderClassName;
// If the type of element needs to change, change it (e.g. password inputs)
type = elem.getAttribute(ATTR_INPUT_TYPE);
if (type) {
elem.type = "text";
} else if (elem.type === "password") {
if (Utils.changeType(elem, "text")) {
elem.setAttribute(ATTR_INPUT_TYPE, "password");
}
}
return true;
}
return false;
}
function handleElem(node, callback) {
var handleInputs, handleTextareas, elem, len, i;
// Check if the passed in node is an input/textarea (in which case it can't have any affected descendants)
if (node && node.getAttribute(ATTR_CURRENT_VAL)) {
callback(node);
} else {
// If an element was passed in, get all affected descendants. Otherwise, get all affected elements in document
handleInputs = node ? node.getElementsByTagName("input") : inputs;
handleTextareas = node ? node.getElementsByTagName("textarea") : textareas;
// Run the callback for each element
for (i = 0, len = handleInputs.length + handleTextareas.length; i < len; i++) {
elem = i < handleInputs.length ? handleInputs[i] : handleTextareas[i - handleInputs.length];
callback(elem);
}
}
}
// Return all affected elements to their normal state (remove placeholder value if present)
function disablePlaceholders(node) {
handleElem(node, hidePlaceholder);
}
// Show the placeholder value on all appropriate elements
function enablePlaceholders(node) {
handleElem(node, showPlaceholder);
}
// Returns a function that is used as a focus event handler
function makeFocusHandler(elem) {
return function () {
// Only hide the placeholder value if the (default) hide-on-focus behaviour is enabled
if (hideOnInput && elem.value === elem.getAttribute(ATTR_CURRENT_VAL) && elem.getAttribute(ATTR_ACTIVE) === "true") {
// Move the caret to the start of the input (this mimics the behaviour of all browsers that do not hide the placeholder on focus)
Utils.moveCaret(elem, 0);
} else {
// Remove the placeholder
hidePlaceholder(elem);
}
};
}
// Returns a function that is used as a blur event handler
function makeBlurHandler(elem) {
return function () {
showPlaceholder(elem);
};
}
// Functions that are used as a event handlers when the hide-on-input behaviour has been activated - very basic implementation of the "input" event
function makeKeydownHandler(elem) {
return function (e) {
keydownVal = elem.value;
//Prevent the use of the arrow keys (try to keep the cursor before the placeholder)
if (elem.getAttribute(ATTR_ACTIVE) === "true") {
if (keydownVal === elem.getAttribute(ATTR_CURRENT_VAL) && Utils.inArray(badKeys, e.keyCode)) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
}
};
}
function makeKeyupHandler(elem) {
return function () {
var type;
if (elem.getAttribute(ATTR_ACTIVE) === "true" && elem.value !== keydownVal) {
// Remove the placeholder
elem.className = elem.className.replace(classNameRegExp, "");
elem.value = elem.value.replace(elem.getAttribute(ATTR_CURRENT_VAL), "");
elem.setAttribute(ATTR_ACTIVE, false);
// If the type of element needs to change, change it (e.g. password inputs)
type = elem.getAttribute(ATTR_INPUT_TYPE);
if (type) {
elem.type = type;
}
}
// If the element is now empty we need to show the placeholder
if (elem.value === "") {
elem.blur();
Utils.moveCaret(elem, 0);
}
};
}
function makeClickHandler(elem) {
return function () {
if (elem === document.activeElement && elem.value === elem.getAttribute(ATTR_CURRENT_VAL) && elem.getAttribute(ATTR_ACTIVE) === "true") {
Utils.moveCaret(elem, 0);
}
};
}
// Returns a function that is used as a submit event handler on form elements that have children affected by this polyfill
function makeSubmitHandler(form) {
return function () {
// Turn off placeholders on all appropriate descendant elements
disablePlaceholders(form);
};
}
// Bind event handlers to an element that we need to affect with the polyfill
function newElement(elem) {
// If the element is part of a form, make sure the placeholder string is not submitted as a value
if (elem.form) {
form = elem.form;
// Set a flag on the form so we know it's been handled (forms can contain multiple inputs)
if (!form.getAttribute(ATTR_FORM_HANDLED)) {
Utils.addEventListener(form, "submit", makeSubmitHandler(form));
form.setAttribute(ATTR_FORM_HANDLED, "true");
}
}
// Bind event handlers to the element so we can hide/show the placeholder as appropriate
Utils.addEventListener(elem, "focus", makeFocusHandler(elem));
Utils.addEventListener(elem, "blur", makeBlurHandler(elem));
// If the placeholder should hide on input rather than on focus we need additional event handlers
if (hideOnInput) {
Utils.addEventListener(elem, "keydown", makeKeydownHandler(elem));
Utils.addEventListener(elem, "keyup", makeKeyupHandler(elem));
Utils.addEventListener(elem, "click", makeClickHandler(elem));
}
// Remember that we've bound event handlers to this element
elem.setAttribute(ATTR_EVENTS_BOUND, "true");
elem.setAttribute(ATTR_CURRENT_VAL, placeholder);
// If the element doesn't have a value, set it to the placeholder string
showPlaceholder(elem);
}
Placeholders.nativeSupport = test.placeholder !== void 0;
if (!Placeholders.nativeSupport) {
// Get references to all the input and textarea elements currently in the DOM (live NodeList objects to we only need to do this once)
inputs = document.getElementsByTagName("input");
textareas = document.getElementsByTagName("textarea");
// Get any settings declared as data-* attributes on the root element (currently the only options are whether to hide the placeholder on focus or input and whether to auto-update)
hideOnInput = root.getAttribute(ATTR_OPTION_FOCUS) === "false";
liveUpdates = root.getAttribute(ATTR_OPTION_LIVE) !== "false";
// Create style element for placeholder styles (instead of directly setting style properties on elements - allows for better flexibility alongside user-defined styles)
styleElem = document.createElement("style");
styleElem.type = "text/css";
// Create style rules as text node
styleRules = document.createTextNode("." + placeholderClassName + " { color:" + placeholderStyleColor + "; }");
// Append style rules to newly created stylesheet
if (styleElem.styleSheet) {
styleElem.styleSheet.cssText = styleRules.nodeValue;
} else {
styleElem.appendChild(styleRules);
}
// Prepend new style element to the head (before any existing stylesheets, so user-defined rules take precedence)
head.insertBefore(styleElem, head.firstChild);
// Set up the placeholders
for (i = 0, len = inputs.length + textareas.length; i < len; i++) {
elem = i < inputs.length ? inputs[i] : textareas[i - inputs.length];
// Get the value of the placeholder attribute, if any. IE10 emulating IE7 fails with getAttribute, hence the use of the attributes node
placeholder = elem.attributes.placeholder;
if (placeholder) {
// IE returns an empty object instead of undefined if the attribute is not present
placeholder = placeholder.nodeValue;
// Only apply the polyfill if this element is of a type that supports placeholders, and has a placeholder attribute with a non-empty value
if (placeholder && Utils.inArray(validTypes, elem.type)) {
newElement(elem);
}
}
}
// If enabled, the polyfill will repeatedly check for changed/added elements and apply to those as well
timer = setInterval(function () {
for (i = 0, len = inputs.length + textareas.length; i < len; i++) {
elem = i < inputs.length ? inputs[i] : textareas[i - inputs.length];
// Only apply the polyfill if this element is of a type that supports placeholders, and has a placeholder attribute with a non-empty value
placeholder = elem.attributes.placeholder;
if (placeholder) {
placeholder = placeholder.nodeValue;
if (placeholder && Utils.inArray(validTypes, elem.type)) {
// If the element hasn't had event handlers bound to it then add them
if (!elem.getAttribute(ATTR_EVENTS_BOUND)) {
newElement(elem);
}
// If the placeholder value has changed or not been initialised yet we need to update the display
if (placeholder !== elem.getAttribute(ATTR_CURRENT_VAL) || (elem.type === "password" && !elem.getAttribute(ATTR_INPUT_TYPE))) {
// Attempt to change the type of password inputs (fails in IE < 9)
if (elem.type === "password" && !elem.getAttribute(ATTR_INPUT_TYPE) && Utils.changeType(elem, "text")) {
elem.setAttribute(ATTR_INPUT_TYPE, "password");
}
// If the placeholder value has changed and the placeholder is currently on display we need to change it
if (elem.value === elem.getAttribute(ATTR_CURRENT_VAL)) {
elem.value = placeholder;
}
// Keep a reference to the current placeholder value in case it changes via another script
elem.setAttribute(ATTR_CURRENT_VAL, placeholder);
}
}
}
}
// If live updates are not enabled cancel the timer
if (!liveUpdates) {
clearInterval(timer);
}
}, 100);
}
// Expose public methods
Placeholders.disable = Placeholders.nativeSupport ? noop : disablePlaceholders;
Placeholders.enable = Placeholders.nativeSupport ? noop : enablePlaceholders;
}(this));