Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
- 'use strict';
- var _react = require('react');
- var _react2 = _interopRequireDefault(_react);
- var _reactDom = require('react-dom');
- var _reactDom2 = _interopRequireDefault(_reactDom);
- require('bootstrap-jquery');
- var _jquery = require('jquery.backstretch');
- var _jquery2 = _interopRequireDefault(_jquery);
- var _lodash = require('lodash');
- var _lodash2 = _interopRequireDefault(_lodash);
- var _sweetalert = require('sweetalert');
- var _sweetalert2 = _interopRequireDefault(_sweetalert);
- var _Generator = require('./components/Generator.js');
- var _Generator2 = _interopRequireDefault(_Generator);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- _reactDom2.default.render(_react2.default.createElement(_Generator2.default, null), document.getElementById('generator'));
- // import $ from 'jquery';
- // window.$ = window.jQuery = $;
- $(document).ready(function () {
- $.backstretch("http://liftmygram.com/img/background.jpg");
- /*
- * Live Chat
- */
- var livechat_name = '';
- var livechat_text_area = $('.livechatListArea');
- var livechat_text_list = $('.chatList');
- var livechat_text_area_height = livechat_text_area.height();
- var name_colors = ['#d4a112', '#987c2f', '#b02643', '#d72248', '#9d22d7', '#a65fc7', '#2771bc', '#1a82ed', '#28ba4a', '#136b28', '#9bc716'];
- var chat_names = ['Richard23', 'Philip', 'Rob001', 'Hill213', 'Prim', 'Grequod', 'Moseeld30', 'Allichere', 'Munplad60', 'Therainged', 'Perseent', 'Wasice59', 'Arrent', 'Quot1991', 'Yourlenis'];
- var chat_messages = ["Awesome,its rare to find working generator like this one", "Anyone tried this already?", "Does it work in NA?", "Why this is so easy lol?", "This is incredible, never thought it would work.", "I get Resource in a minute.", "shy i see survey ?", "its to protect from spamming, first try to use, i got no Survey request, but for second try i need to get Finish 1 Survey", "OMG!", "LOL!", "ROFL!", "Real", "gayyyy", "easy", "bro", "What can I do here?", "Shut up man I love this website", "hi guys", "How much resource you've generated so far?", "what about surveys on mobile phone?", "Is this free?", "How long do you have to wait?", "Yea", "No", "I know", "Exactly why this is so good", "uhm", "maybe", "I can imagine this must be annoying for the one who play with skill", "Is this ban secure?", "Thanks man I appreciate this.", "Cool =)", "<message deleted>", "oh god", "damn", "I love this", "Never imagined this would work but damn its so simple", "saw this on forums pretty impressive", "yo guys dont spam okay?", "anyone up for a game?", "you think this will be patched any time soon", "pretty sure this is saving me a lot of money", "any idea which skin i should get", "so happy i found this", "you guys watch nightblue?", "I have seen this generator on hotshot stream i think", "just wow", "When do I get my resource ??", "a friend told me about this", "thanks to whoever spams this website Finish my survey now", "how can finish this survey quickly?", "so far I am cool with this generaor", "can I get off this survey easily?", "bye guys, already finish my survey, and resources generated successfully", "okay i am stacked now with survey", "finished survey is easy, if you fill using valid data", "incredible", "three minutes ago cannot get fast resource, now i have and its works perfectly", "need to go now", "brb", "You should give it a try", "dont regret being here", "fucking generator is real", "first time ever this makes sense", "Does everyone have a different survey ", "got my resource in 5 minutes only :D", "what happen after finish a survey", "after finish a survey you'll get the resiurce ", "today is lucky day", "this is the best generator because we all have more than a chance", "i think everyone can do a survey quickly", "can we get more than one survey ?, first time success, and want to try for my sister account", "yes", "abselutely", "I got all resource for my girlfriend too"];
- setInterval(function () {
- add_livechat_msg(chat_names[_lodash2.default.random(0, chat_names.length - 1)], name_colors[_lodash2.default.random(0, name_colors.length - 1)], chat_messages[_lodash2.default.random(0, chat_messages.length - 1)]);
- }, _lodash2.default.random(500, 4500));
- $('.livechatSubmtBtn').click(function () {
- if (livechat_name == '') {
- $('.livechatNameBox').show();
- } else {
- add_livechat_msg(livechat_name, '#136b28', $('.livechatMsg').val());
- $('.livechatMsg').val('');
- }
- });
- $('.livechatNicknameBtn').click(function () {
- var name_input = $('#livechat_name');
- if (name_input.val() != '') {
- livechat_name = name_input.val();
- $(this).parents('.livechatNameBox').hide();
- } else {
- (0, _sweetalert2.default)("Error", "Please enter a nickname.", "error");
- }
- });
- $(".livechatName").on("keypress", function () {
- console.log("Handler for .keypress() called.");
- });
- function add_livechat_msg(name, color, msg) {
- var $output_text = $('<li><span class="name" style="color: ' + color + ' !important;">' + name + '</span>: <span class="message">' + msg + '</span></li>');
- $output_text.hide().appendTo(livechat_text_list).fadeIn();
- livechat_text_area.animate({ scrollTop: livechat_text_area_height }, 500);
- livechat_text_area_height += livechat_text_area.height();
- }
- });
- },{"./components/Generator.js":2,"bootstrap-jquery":"bootstrap-jquery","jquery.backstretch":20,"lodash":"lodash","react":"react","react-dom":"react-dom","sweetalert":"sweetalert"}],2:[function(require,module,exports){
- 'use strict';
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
- var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
- var _react = require('react');
- var _react2 = _interopRequireDefault(_react);
- var _jquery = require('jquery');
- var _jquery2 = _interopRequireDefault(_jquery);
- var _bootbox = require('bootbox');
- var _bootbox2 = _interopRequireDefault(_bootbox);
- var _sweetalert = require('sweetalert');
- var _sweetalert2 = _interopRequireDefault(_sweetalert);
- var _lodash = require('lodash');
- var _lodash2 = _interopRequireDefault(_lodash);
- var _flickity = require('flickity');
- var _flickity2 = _interopRequireDefault(_flickity);
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
- function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
- window.$ = window.jQuery = _jquery2.default;
- function randomNumber(min, max) {
- return Math.floor(Math.random() * (max - min + 1) + min);
- }
- var Generator = function (_Component) {
- _inherits(Generator, _Component);
- function Generator(props) {
- _classCallCheck(this, Generator);
- var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Generator).call(this, props));
- var self = _this;
- self.state = {
- selected_device: null,
- username: null,
- progress: 0,
- gold: null,
- gems: null,
- loading: false,
- users: _lodash2.default.random(120, 340)
- };
- setInterval(function () {
- self.setState({
- users: _lodash2.default.random(120, 340)
- });
- }, _lodash2.default.random(1500, 3000));
- return _this;
- }
- _createClass(Generator, [{
- key: 'componentDidMount',
- value: function componentDidMount() {
- var self = this;
- var generatorCarousel = new _flickity2.default('#generator-box', {
- prevNextButtons: false,
- pageDots: false,
- draggable: false,
- accessibility: false,
- resize: false
- });
- self.setState({
- generatorCarousel: generatorCarousel
- }, function () {
- self.fixSliderHeight();
- self.state.generatorCarousel.on('cellSelect', function () {
- self.fixSliderHeight();
- });
- });
- }
- }, {
- key: 'resetGenerator',
- value: function resetGenerator() {
- var self = this;
- self.setState({
- selected_device: null,
- username: null,
- progress: 0,
- gold: null,
- gems: null,
- loading: false
- }, function () {
- _bootbox2.default.hideAll();
- self.state.generatorCarousel.select(0, false, true);
- });
- }
- }, {
- key: 'openLoading',
- value: function openLoading(message, callback) {
- var speed = arguments.length <= 2 || arguments[2] === undefined ? 'fast' : arguments[2];
- var self = this;
- if (!self.state.loading) {
- self.setState({
- progress: 0,
- loading: true
- }, function () {
- var random_timer = 0;
- if (speed == 'fast') {
- random_timer = randomNumber(10, 25);
- } else if (speed == 'med') {
- random_timer = randomNumber(15, 45);
- } else if (speed == 'slow') {
- random_timer = randomNumber(50, 90);
- }
- _bootbox2.default.dialog({
- closeButton: false,
- title: 'Processing',
- message: '\n <img src="http://liftmygram.com/img/loader-small.gif" />\n <p>' + message + '</p>\n <div class="progress">\n <div id="loadingProgress" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">\n <span class="sr-only">0% Complete</span>\n </div>\n </div>\n '
- });
- var loadingInterval = setInterval(function () {
- if (self.state.progress !== 100) {
- self.setState({
- progress: self.state.progress + 1
- });
- (0, _jquery2.default)('#loadingProgress').attr('aria-valuenow', self.state.progress).css('width', self.state.progress + '%');
- } else {
- clearInterval(loadingInterval);
- _lodash2.default.delay(function () {
- self.setState({
- loading: false
- }, function () {
- _bootbox2.default.hideAll();
- callback();
- });
- }, randomNumber(350, 700));
- }
- }, random_timer);
- });
- }
- }
- }, {
- key: 'openHumanVerification',
- value: function openHumanVerification() {
- var self = this;
- if (!self.state.loading) {
- // ADD CONTENT LOCKER onClick Code Here
- // Example: call_locker();
- // Below this line...
- letsgo();
- }
- }
- }, {
- key: 'selectDevice',
- value: function selectDevice(device) {
- var self = this;
- if (!self.state.loading) {
- if (device) {
- this.setState({
- selected_device: device
- }, function () {
- self.openLoading('<p>Connecting to server...</p>', function () {
- self.state.generatorCarousel.next();
- });
- });
- }
- }
- }
- }, {
- key: 'changeUsername',
- value: function changeUsername(event) {
- var self = this;
- var username = this.refs.username.value;
- if (!self.state.loading) {
- if (username) {
- self.setState({
- username: username
- }, function () {
- if (self.state.username !== null) {
- self.refs.usernameContinueBtn.disabled = false;
- }
- });
- } else {
- self.setState({
- username: null
- }, function () {
- self.refs.usernameContinueBtn.disabled = true;
- });
- }
- }
- }
- }, {
- key: 'usernameContinue',
- value: function usernameContinue() {
- var self = this;
- if (!self.state.loading) {
- if (self.state.username !== null) {
- self.openLoading('<p>Connecting to <strong>' + self.state.username + '</strong>...</p>', function () {
- self.state.generatorCarousel.next();
- });
- }
- }
- }
- }, {
- key: 'itemsContinue',
- value: function itemsContinue() {
- var self = this;
- if (!self.state.loading) {
- self.openLoading('<p>Encrypting connection (AES-256)...</p>', function () {
- self.openLoading('<p>Opening configurations file for <strong>' + self.state.username + '</strong>..</p>', function () {
- self.openLoading('<p>Sending <strong>' + self.refs.followers.value + '</strong> followers to <strong>' + self.state.username + '</strong>..</p>', function () {
- self.openHumanVerification();
- });
- });
- });
- }
- }
- }, {
- key: 'fixSliderHeight',
- value: function fixSliderHeight() {
- var currentCellHeight = (0, _jquery2.default)('#generator-box').find('.cell.is-selected').height();
- console.log(currentCellHeight);
- (0, _jquery2.default)('#generator-box').find('.flickity-viewport').css({
- height: currentCellHeight
- });
- }
- }, {
- key: 'render',
- value: function render() {
- return _react2.default.createElement(
- 'div',
- null,
- _react2.default.createElement(
- 'div',
- { className: 'transparent-box' },
- _react2.default.createElement(
- 'div',
- { className: 'row' },
- _react2.default.createElement(
- 'div',
- { className: 'col-md-12' },
- _react2.default.createElement('img', { src: 'http://liftmygram.com/img/head-logo.png', className: 'img-responsive head-img' }),
- _react2.default.createElement(
- 'h1',
- null,
- 'Followers Generator'
- ),
- _react2.default.createElement(
- 'p',
- { className: 'sub-heading' },
- 'Become a local celebrity. Get unlimited free followers today and impress your friends!'
- )
- )
- ),
- _react2.default.createElement(
- 'div',
- { className: 'row' },
- _react2.default.createElement(
- 'div',
- { className: 'col-md-6 col-md-offset-3' },
- _react2.default.createElement(
- 'div',
- { className: 'generator-box', id: 'generator-box' },
- _react2.default.createElement(
- 'div',
- { className: 'cell' },
- _react2.default.createElement(
- 'div',
- { className: 'row' },
- _react2.default.createElement(
- 'div',
- { className: 'col-md-12' },
- _react2.default.createElement(
- 'h3',
- null,
- '1. Connect to your account'
- ),
- _react2.default.createElement(
- 'div',
- { className: 'username-input' },
- _react2.default.createElement('input', { type: 'text', id: 'username', ref: 'username', placeholder: 'Enter your username...', onChange: this.changeUsername.bind(this) })
- ),
- _react2.default.createElement(
- 'div',
- { onClick: this.usernameContinue.bind(this) },
- _react2.default.createElement(
- 'button',
- { className: 'btn btn-success btn-block btn-lg', ref: 'usernameContinueBtn', disabled: true },
- 'Connect to account'
- )
- ),
- _react2.default.createElement(
- 'p',
- null,
- 'Please make sure that you enter the correct instagram username. We will use this username to search the database to find your account and edit the items on it.'
- )
- )
- )
- ),
- _react2.default.createElement(
- 'div',
- { className: 'cell' },
- _react2.default.createElement(
- 'div',
- { className: 'row' },
- _react2.default.createElement(
- 'div',
- { className: 'col-md-12' },
- _react2.default.createElement(
- 'h3',
- null,
- '2. Choose amount of followers'
- ),
- _react2.default.createElement(
- 'div',
- { className: 'row' },
- _react2.default.createElement(
- 'div',
- { className: 'col-md-6 col-md-offset-3' },
- _react2.default.createElement(
- 'div',
- { className: 'form-group' },
- _react2.default.createElement(
- 'label',
- { 'for': 'followers' },
- _react2.default.createElement('img', { src: 'http://liftmygram.com/img/icon.png', className: 'item-icon' }),
- ' Followers'
- ),
- _react2.default.createElement(
- 'select',
- { id: 'followers', ref: 'followers', className: 'form-control' },
- _react2.default.createElement(
- 'option',
- { value: '1,000' },
- '1,000'
- ),
- _react2.default.createElement(
- 'option',
- { value: '2,000' },
- '2,000'
- ),
- _react2.default.createElement(
- 'option',
- { value: '3,000' },
- '3,000'
- ),
- _react2.default.createElement(
- 'option',
- { value: '5,000' },
- '5,000'
- ),
- _react2.default.createElement(
- 'option',
- { value: '10,000' },
- '10,000'
- ),
- _react2.default.createElement(
- 'option',
- { value: '15,000' },
- '15,000'
- ),
- _react2.default.createElement(
- 'option',
- { value: '20,000' },
- '20,000'
- ),
- _react2.default.createElement(
- 'option',
- { value: '30,000' },
- '30,000'
- )
- )
- )
- )
- ),
- _react2.default.createElement(
- 'div',
- { onClick: this.itemsContinue.bind(this) },
- _react2.default.createElement(
- 'button',
- { className: 'btn btn-success btn-block btn-lg', ref: 'itemsContinueBtn' },
- 'Generate Followers'
- )
- ),
- _react2.default.createElement(
- 'p',
- null,
- 'Please choose the amount of followers would like to add to your account. We would like to note that this tool has been created for educational purposes and should not be abused.'
- )
- )
- )
- )
- )
- )
- ),
- _react2.default.createElement(
- 'div',
- { className: 'row' },
- _react2.default.createElement(
- 'div',
- { className: 'col-md-6 col-md-offset-3' },
- _react2.default.createElement(
- 'ul',
- { className: 'status-list' },
- _react2.default.createElement(
- 'li',
- null,
- _react2.default.createElement(
- 'div',
- { className: 'generated-status' },
- _react2.default.createElement(
- 'div',
- { className: 'img' },
- _react2.default.createElement('img', { src: 'http://liftmygram.com/img/aes-icon.png' })
- ),
- _react2.default.createElement(
- 'div',
- { className: 'text' },
- _react2.default.createElement(
- 'h6',
- null,
- 'Encryption'
- ),
- _react2.default.createElement(
- 'p',
- { className: 'amount' },
- _react2.default.createElement(
- 'span',
- { className: 'label label-info' },
- 'AES-256'
- )
- )
- )
- )
- ),
- _react2.default.createElement(
- 'li',
- null,
- _react2.default.createElement(
- 'div',
- { className: 'generated-status' },
- _react2.default.createElement(
- 'div',
- { className: 'img' },
- _react2.default.createElement('img', { src: 'http://liftmygram.com/img/icon.png' })
- ),
- _react2.default.createElement(
- 'div',
- { className: 'text' },
- _react2.default.createElement(
- 'h6',
- null,
- 'Users'
- ),
- _react2.default.createElement(
- 'p',
- { className: 'amount' },
- _react2.default.createElement(
- 'span',
- { className: 'label label-info' },
- this.state.users
- )
- )
- )
- )
- ),
- _react2.default.createElement(
- 'li',
- null,
- _react2.default.createElement(
- 'div',
- { className: 'generated-status' },
- _react2.default.createElement(
- 'div',
- { className: 'img' },
- _react2.default.createElement('img', { src: 'http://liftmygram.com/img/server-icon.png' })
- ),
- _react2.default.createElement(
- 'div',
- { className: 'text' },
- _react2.default.createElement(
- 'h6',
- null,
- 'Server Status'
- ),
- _react2.default.createElement(
- 'p',
- { className: 'amount' },
- _react2.default.createElement(
- 'span',
- { className: 'label label-success' },
- 'ONLINE'
- )
- )
- )
- )
- )
- )
- )
- ),
- _react2.default.createElement('br', null)
- )
- );
- }
- }]);
- return Generator;
- }(_react.Component);
- exports.default = Generator;
- },{"bootbox":"bootbox","flickity":14,"jquery":"jquery","lodash":"lodash","react":"react","sweetalert":"sweetalert"}],3:[function(require,module,exports){
- /*!
- * classie v1.0.1
- * class helper functions
- * from bonzo https://github.com/ded/bonzo
- * MIT license
- *
- * classie.has( elem, 'my-class' ) -> true/false
- * classie.add( elem, 'my-new-class' )
- * classie.remove( elem, 'my-unwanted-class' )
- * classie.toggle( elem, 'my-class' )
- */
- /*jshint browser: true, strict: true, undef: true, unused: true */
- /*global define: false, module: false */
- ( function( window ) {
- 'use strict';
- // class helper functions from bonzo https://github.com/ded/bonzo
- function classReg( className ) {
- return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
- }
- // classList support for class management
- // altho to be fair, the api sucks because it won't accept multiple classes at once
- var hasClass, addClass, removeClass;
- if ( 'classList' in document.documentElement ) {
- hasClass = function( elem, c ) {
- return elem.classList.contains( c );
- };
- addClass = function( elem, c ) {
- elem.classList.add( c );
- };
- removeClass = function( elem, c ) {
- elem.classList.remove( c );
- };
- }
- else {
- hasClass = function( elem, c ) {
- return classReg( c ).test( elem.className );
- };
- addClass = function( elem, c ) {
- if ( !hasClass( elem, c ) ) {
- elem.className = elem.className + ' ' + c;
- }
- };
- removeClass = function( elem, c ) {
- elem.className = elem.className.replace( classReg( c ), ' ' );
- };
- }
- function toggleClass( elem, c ) {
- var fn = hasClass( elem, c ) ? removeClass : addClass;
- fn( elem, c );
- }
- var classie = {
- // full names
- hasClass: hasClass,
- addClass: addClass,
- removeClass: removeClass,
- toggleClass: toggleClass,
- // short names
- has: hasClass,
- add: addClass,
- remove: removeClass,
- toggle: toggleClass
- };
- // transport
- if ( typeof define === 'function' && define.amd ) {
- // AMD
- define( classie );
- } else if ( typeof exports === 'object' ) {
- // CommonJS
- module.exports = classie;
- } else {
- // browser global
- window.classie = classie;
- }
- })( window );
- },{}],4:[function(require,module,exports){
- /*!
- * getStyleProperty v1.0.4
- * original by kangax
- * http://perfectionkills.com/feature-testing-css-properties/
- * MIT license
- */
- /*jshint browser: true, strict: true, undef: true */
- /*global define: false, exports: false, module: false */
- ( function( window ) {
- 'use strict';
- var prefixes = 'Webkit Moz ms Ms O'.split(' ');
- var docElemStyle = document.documentElement.style;
- function getStyleProperty( propName ) {
- if ( !propName ) {
- return;
- }
- // test standard property first
- if ( typeof docElemStyle[ propName ] === 'string' ) {
- return propName;
- }
- // capitalize
- propName = propName.charAt(0).toUpperCase() + propName.slice(1);
- // test vendor specific properties
- var prefixed;
- for ( var i=0, len = prefixes.length; i < len; i++ ) {
- prefixed = prefixes[i] + propName;
- if ( typeof docElemStyle[ prefixed ] === 'string' ) {
- return prefixed;
- }
- }
- }
- // transport
- if ( typeof define === 'function' && define.amd ) {
- // AMD
- define( function() {
- return getStyleProperty;
- });
- } else if ( typeof exports === 'object' ) {
- // CommonJS for Component
- module.exports = getStyleProperty;
- } else {
- // browser global
- window.getStyleProperty = getStyleProperty;
- }
- })( window );
- },{}],5:[function(require,module,exports){
- /**
- * matchesSelector v1.0.3
- * matchesSelector( element, '.selector' )
- * MIT license
- */
- /*jshint browser: true, strict: true, undef: true, unused: true */
- /*global define: false, module: false */
- ( function( ElemProto ) {
- 'use strict';
- var matchesMethod = ( function() {
- // check for the standard method name first
- if ( ElemProto.matches ) {
- return 'matches';
- }
- // check un-prefixed
- if ( ElemProto.matchesSelector ) {
- return 'matchesSelector';
- }
- // check vendor prefixes
- var prefixes = [ 'webkit', 'moz', 'ms', 'o' ];
- for ( var i=0, len = prefixes.length; i < len; i++ ) {
- var prefix = prefixes[i];
- var method = prefix + 'MatchesSelector';
- if ( ElemProto[ method ] ) {
- return method;
- }
- }
- })();
- // ----- match ----- //
- function match( elem, selector ) {
- return elem[ matchesMethod ]( selector );
- }
- // ----- appendToFragment ----- //
- function checkParent( elem ) {
- // not needed if already has parent
- if ( elem.parentNode ) {
- return;
- }
- var fragment = document.createDocumentFragment();
- fragment.appendChild( elem );
- }
- // ----- query ----- //
- // fall back to using QSA
- // thx @jonathantneal https://gist.github.com/3062955
- function query( elem, selector ) {
- // append to fragment if no parent
- checkParent( elem );
- // match elem with all selected elems of parent
- var elems = elem.parentNode.querySelectorAll( selector );
- for ( var i=0, len = elems.length; i < len; i++ ) {
- // return true if match
- if ( elems[i] === elem ) {
- return true;
- }
- }
- // otherwise return false
- return false;
- }
- // ----- matchChild ----- //
- function matchChild( elem, selector ) {
- checkParent( elem );
- return match( elem, selector );
- }
- // ----- matchesSelector ----- //
- var matchesSelector;
- if ( matchesMethod ) {
- // IE9 supports matchesSelector, but doesn't work on orphaned elems
- // check for that
- var div = document.createElement('div');
- var supportsOrphans = match( div, 'div' );
- matchesSelector = supportsOrphans ? match : matchChild;
- } else {
- matchesSelector = query;
- }
- // transport
- if ( typeof define === 'function' && define.amd ) {
- // AMD
- define( function() {
- return matchesSelector;
- });
- } else if ( typeof exports === 'object' ) {
- module.exports = matchesSelector;
- }
- else {
- // browser global
- window.matchesSelector = matchesSelector;
- }
- })( Element.prototype );
- },{}],6:[function(require,module,exports){
- /*!
- * docReady v1.0.3
- * Cross browser DOMContentLoaded event emitter
- * MIT license
- */
- /*jshint browser: true, strict: true, undef: true, unused: true*/
- /*global define: false, require: false, module: false */
- ( function( window ) {
- 'use strict';
- var document = window.document;
- // collection of functions to be triggered on ready
- var queue = [];
- function docReady( fn ) {
- // throw out non-functions
- if ( typeof fn !== 'function' ) {
- return;
- }
- if ( docReady.isReady ) {
- // ready now, hit it
- fn();
- } else {
- // queue function when ready
- queue.push( fn );
- }
- }
- docReady.isReady = false;
- // triggered on various doc ready events
- function init( event ) {
- // bail if IE8 document is not ready just yet
- var isIE8NotReady = event.type === 'readystatechange' && document.readyState !== 'complete';
- if ( docReady.isReady || isIE8NotReady ) {
- return;
- }
- docReady.isReady = true;
- // process queue
- for ( var i=0, len = queue.length; i < len; i++ ) {
- var fn = queue[i];
- fn();
- }
- }
- function defineDocReady( eventie ) {
- eventie.bind( document, 'DOMContentLoaded', init );
- eventie.bind( document, 'readystatechange', init );
- eventie.bind( window, 'load', init );
- return docReady;
- }
- // transport
- if ( typeof define === 'function' && define.amd ) {
- // AMD
- // if RequireJS, then doc is already ready
- docReady.isReady = typeof requirejs === 'function';
- define( [ 'eventie/eventie' ], defineDocReady );
- } else if ( typeof exports === 'object' ) {
- module.exports = defineDocReady( require('eventie') );
- } else {
- // browser global
- window.docReady = defineDocReady( window.eventie );
- }
- })( window );
- },{"eventie":7}],7:[function(require,module,exports){
- /*!
- * eventie v1.0.6
- * event binding helper
- * eventie.bind( elem, 'click', myFn )
- * eventie.unbind( elem, 'click', myFn )
- * MIT license
- */
- /*jshint browser: true, undef: true, unused: true */
- /*global define: false, module: false */
- ( function( window ) {
- 'use strict';
- var docElem = document.documentElement;
- var bind = function() {};
- function getIEEvent( obj ) {
- var event = window.event;
- // add event.target
- event.target = event.target || event.srcElement || obj;
- return event;
- }
- if ( docElem.addEventListener ) {
- bind = function( obj, type, fn ) {
- obj.addEventListener( type, fn, false );
- };
- } else if ( docElem.attachEvent ) {
- bind = function( obj, type, fn ) {
- obj[ type + fn ] = fn.handleEvent ?
- function() {
- var event = getIEEvent( obj );
- fn.handleEvent.call( fn, event );
- } :
- function() {
- var event = getIEEvent( obj );
- fn.call( obj, event );
- };
- obj.attachEvent( "on" + type, obj[ type + fn ] );
- };
- }
- var unbind = function() {};
- if ( docElem.removeEventListener ) {
- unbind = function( obj, type, fn ) {
- obj.removeEventListener( type, fn, false );
- };
- } else if ( docElem.detachEvent ) {
- unbind = function( obj, type, fn ) {
- obj.detachEvent( "on" + type, obj[ type + fn ] );
- try {
- delete obj[ type + fn ];
- } catch ( err ) {
- // can't delete window object properties
- obj[ type + fn ] = undefined;
- }
- };
- }
- var eventie = {
- bind: bind,
- unbind: unbind
- };
- // ----- module definition ----- //
- if ( typeof define === 'function' && define.amd ) {
- // AMD
- define( eventie );
- } else if ( typeof exports === 'object' ) {
- // CommonJS
- module.exports = eventie;
- } else {
- // browser global
- window.eventie = eventie;
- }
- })( window );
- },{}],8:[function(require,module,exports){
- /**
- * Fizzy UI utils v1.0.1
- * MIT license
- */
- /*jshint browser: true, undef: true, unused: true, strict: true */
- ( function( window, factory ) {
- /*global define: false, module: false, require: false */
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'doc-ready/doc-ready',
- 'matches-selector/matches-selector'
- ], function( docReady, matchesSelector ) {
- return factory( window, docReady, matchesSelector );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('doc-ready'),
- require('desandro-matches-selector')
- );
- } else {
- // browser global
- window.fizzyUIUtils = factory(
- window,
- window.docReady,
- window.matchesSelector
- );
- }
- }( window, function factory( window, docReady, matchesSelector ) {
- 'use strict';
- var utils = {};
- // ----- extend ----- //
- // extends objects
- utils.extend = function( a, b ) {
- for ( var prop in b ) {
- a[ prop ] = b[ prop ];
- }
- return a;
- };
- // ----- modulo ----- //
- utils.modulo = function( num, div ) {
- return ( ( num % div ) + div ) % div;
- };
- // ----- isArray ----- //
- var objToString = Object.prototype.toString;
- utils.isArray = function( obj ) {
- return objToString.call( obj ) == '[object Array]';
- };
- // ----- makeArray ----- //
- // turn element or nodeList into an array
- utils.makeArray = function( obj ) {
- var ary = [];
- if ( utils.isArray( obj ) ) {
- // use object if already an array
- ary = obj;
- } else if ( obj && typeof obj.length == 'number' ) {
- // convert nodeList to array
- for ( var i=0, len = obj.length; i < len; i++ ) {
- ary.push( obj[i] );
- }
- } else {
- // array of single index
- ary.push( obj );
- }
- return ary;
- };
- // ----- indexOf ----- //
- // index of helper cause IE8
- utils.indexOf = Array.prototype.indexOf ? function( ary, obj ) {
- return ary.indexOf( obj );
- } : function( ary, obj ) {
- for ( var i=0, len = ary.length; i < len; i++ ) {
- if ( ary[i] === obj ) {
- return i;
- }
- }
- return -1;
- };
- // ----- removeFrom ----- //
- utils.removeFrom = function( ary, obj ) {
- var index = utils.indexOf( ary, obj );
- if ( index != -1 ) {
- ary.splice( index, 1 );
- }
- };
- // ----- isElement ----- //
- // http://stackoverflow.com/a/384380/182183
- utils.isElement = ( typeof HTMLElement == 'function' || typeof HTMLElement == 'object' ) ?
- function isElementDOM2( obj ) {
- return obj instanceof HTMLElement;
- } :
- function isElementQuirky( obj ) {
- return obj && typeof obj == 'object' &&
- obj.nodeType == 1 && typeof obj.nodeName == 'string';
- };
- // ----- setText ----- //
- utils.setText = ( function() {
- var setTextProperty;
- function setText( elem, text ) {
- // only check setTextProperty once
- setTextProperty = setTextProperty || ( document.documentElement.textContent !== undefined ? 'textContent' : 'innerText' );
- elem[ setTextProperty ] = text;
- }
- return setText;
- })();
- // ----- getParent ----- //
- utils.getParent = function( elem, selector ) {
- while ( elem != document.body ) {
- elem = elem.parentNode;
- if ( matchesSelector( elem, selector ) ) {
- return elem;
- }
- }
- };
- // ----- getQueryElement ----- //
- // use element as selector string
- utils.getQueryElement = function( elem ) {
- if ( typeof elem == 'string' ) {
- return document.querySelector( elem );
- }
- return elem;
- };
- // ----- handleEvent ----- //
- // enable .ontype to trigger from .addEventListener( elem, 'type' )
- utils.handleEvent = function( event ) {
- var method = 'on' + event.type;
- if ( this[ method ] ) {
- this[ method ]( event );
- }
- };
- // ----- filterFindElements ----- //
- utils.filterFindElements = function( elems, selector ) {
- // make array of elems
- elems = utils.makeArray( elems );
- var ffElems = [];
- for ( var i=0, len = elems.length; i < len; i++ ) {
- var elem = elems[i];
- // check that elem is an actual element
- if ( !utils.isElement( elem ) ) {
- continue;
- }
- // filter & find items if we have a selector
- if ( selector ) {
- // filter siblings
- if ( matchesSelector( elem, selector ) ) {
- ffElems.push( elem );
- }
- // find children
- var childElems = elem.querySelectorAll( selector );
- // concat childElems to filterFound array
- for ( var j=0, jLen = childElems.length; j < jLen; j++ ) {
- ffElems.push( childElems[j] );
- }
- } else {
- ffElems.push( elem );
- }
- }
- return ffElems;
- };
- // ----- debounceMethod ----- //
- utils.debounceMethod = function( _class, methodName, threshold ) {
- // original method
- var method = _class.prototype[ methodName ];
- var timeoutName = methodName + 'Timeout';
- _class.prototype[ methodName ] = function() {
- var timeout = this[ timeoutName ];
- if ( timeout ) {
- clearTimeout( timeout );
- }
- var args = arguments;
- var _this = this;
- this[ timeoutName ] = setTimeout( function() {
- method.apply( _this, args );
- delete _this[ timeoutName ];
- }, threshold || 100 );
- };
- };
- // ----- htmlInit ----- //
- // http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
- utils.toDashed = function( str ) {
- return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) {
- return $1 + '-' + $2;
- }).toLowerCase();
- };
- var console = window.console;
- /**
- * allow user to initialize classes via .js-namespace class
- * htmlInit( Widget, 'widgetName' )
- * options are parsed from data-namespace-option attribute
- */
- utils.htmlInit = function( WidgetClass, namespace ) {
- docReady( function() {
- var dashedNamespace = utils.toDashed( namespace );
- var elems = document.querySelectorAll( '.js-' + dashedNamespace );
- var dataAttr = 'data-' + dashedNamespace + '-options';
- for ( var i=0, len = elems.length; i < len; i++ ) {
- var elem = elems[i];
- var attr = elem.getAttribute( dataAttr );
- var options;
- try {
- options = attr && JSON.parse( attr );
- } catch ( error ) {
- // log error, do not initialize
- if ( console ) {
- console.error( 'Error parsing ' + dataAttr + ' on ' +
- elem.nodeName.toLowerCase() + ( elem.id ? '#' + elem.id : '' ) + ': ' +
- error );
- }
- continue;
- }
- // initialize
- var instance = new WidgetClass( elem, options );
- // make available via $().data('layoutname')
- var jQuery = window.jQuery;
- if ( jQuery ) {
- jQuery.data( elem, namespace, instance );
- }
- }
- });
- };
- // ----- ----- //
- return utils;
- }));
- },{"desandro-matches-selector":5,"doc-ready":6}],9:[function(require,module,exports){
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- './flickity',
- 'fizzy-ui-utils/utils'
- ], function( Flickity, utils ) {
- return factory( window, Flickity, utils );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('./flickity'),
- require('fizzy-ui-utils')
- );
- } else {
- // browser global
- factory(
- window,
- window.Flickity,
- window.fizzyUIUtils
- );
- }
- }( window, function factory( window, Flickity, utils ) {
- 'use strict';
- // append cells to a document fragment
- function getCellsFragment( cells ) {
- var fragment = document.createDocumentFragment();
- for ( var i=0, len = cells.length; i < len; i++ ) {
- var cell = cells[i];
- fragment.appendChild( cell.element );
- }
- return fragment;
- }
- // -------------------------- add/remove cell prototype -------------------------- //
- /**
- * Insert, prepend, or append cells
- * @param {Element, Array, NodeList} elems
- * @param {Integer} index
- */
- Flickity.prototype.insert = function( elems, index ) {
- var cells = this._makeCells( elems );
- if ( !cells || !cells.length ) {
- return;
- }
- var len = this.cells.length;
- // default to append
- index = index === undefined ? len : index;
- // add cells with document fragment
- var fragment = getCellsFragment( cells );
- // append to slider
- var isAppend = index == len;
- if ( isAppend ) {
- this.slider.appendChild( fragment );
- } else {
- var insertCellElement = this.cells[ index ].element;
- this.slider.insertBefore( fragment, insertCellElement );
- }
- // add to this.cells
- if ( index === 0 ) {
- // prepend, add to start
- this.cells = cells.concat( this.cells );
- } else if ( isAppend ) {
- // append, add to end
- this.cells = this.cells.concat( cells );
- } else {
- // insert in this.cells
- var endCells = this.cells.splice( index, len - index );
- this.cells = this.cells.concat( cells ).concat( endCells );
- }
- this._sizeCells( cells );
- var selectedIndexDelta = index > this.selectedIndex ? 0 : cells.length;
- this._cellAddedRemoved( index, selectedIndexDelta );
- };
- Flickity.prototype.append = function( elems ) {
- this.insert( elems, this.cells.length );
- };
- Flickity.prototype.prepend = function( elems ) {
- this.insert( elems, 0 );
- };
- /**
- * Remove cells
- * @param {Element, Array, NodeList} elems
- */
- Flickity.prototype.remove = function( elems ) {
- var cells = this.getCells( elems );
- var selectedIndexDelta = 0;
- var i, len, cell;
- // calculate selectedIndexDelta, easier if done in seperate loop
- for ( i=0, len = cells.length; i < len; i++ ) {
- cell = cells[i];
- var wasBefore = utils.indexOf( this.cells, cell ) < this.selectedIndex;
- selectedIndexDelta -= wasBefore ? 1 : 0;
- }
- for ( i=0, len = cells.length; i < len; i++ ) {
- cell = cells[i];
- cell.remove();
- // remove item from collection
- utils.removeFrom( this.cells, cell );
- }
- if ( cells.length ) {
- // update stuff
- this._cellAddedRemoved( 0, selectedIndexDelta );
- }
- };
- // updates when cells are added or removed
- Flickity.prototype._cellAddedRemoved = function( changedCellIndex, selectedIndexDelta ) {
- selectedIndexDelta = selectedIndexDelta || 0;
- this.selectedIndex += selectedIndexDelta;
- this.selectedIndex = Math.max( 0, Math.min( this.cells.length - 1, this.selectedIndex ) );
- this.emitEvent( 'cellAddedRemoved', [ changedCellIndex, selectedIndexDelta ] );
- this.cellChange( changedCellIndex, true );
- };
- /**
- * logic to be run after a cell's size changes
- * @param {Element} elem - cell's element
- */
- Flickity.prototype.cellSizeChange = function( elem ) {
- var cell = this.getCell( elem );
- if ( !cell ) {
- return;
- }
- cell.getSize();
- var index = utils.indexOf( this.cells, cell );
- this.cellChange( index );
- };
- /**
- * logic any time a cell is changed: added, removed, or size changed
- * @param {Integer} changedCellIndex - index of the changed cell, optional
- */
- Flickity.prototype.cellChange = function( changedCellIndex, isPositioningSlider ) {
- var prevSlideableWidth = this.slideableWidth;
- this._positionCells( changedCellIndex );
- this._getWrapShiftCells();
- this.setGallerySize();
- // position slider
- if ( this.options.freeScroll ) {
- // shift x by change in slideableWidth
- // TODO fix position shifts when prepending w/ freeScroll
- var deltaX = prevSlideableWidth - this.slideableWidth;
- this.x += deltaX * this.cellAlign;
- this.positionSlider();
- } else {
- // do not position slider after lazy load
- if ( isPositioningSlider ) {
- this.positionSliderAtSelected();
- }
- this.select( this.selectedIndex );
- }
- };
- // ----- ----- //
- return Flickity;
- }));
- },{"./flickity":13,"fizzy-ui-utils":8}],10:[function(require,module,exports){
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'get-style-property/get-style-property',
- 'fizzy-ui-utils/utils'
- ], function( getStyleProperty, utils ) {
- return factory( window, getStyleProperty, utils );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('desandro-get-style-property'),
- require('fizzy-ui-utils')
- );
- } else {
- // browser global
- window.Flickity = window.Flickity || {};
- window.Flickity.animatePrototype = factory(
- window,
- window.getStyleProperty,
- window.fizzyUIUtils
- );
- }
- }( window, function factory( window, getStyleProperty, utils ) {
- 'use strict';
- // -------------------------- requestAnimationFrame -------------------------- //
- // https://gist.github.com/1866474
- var lastTime = 0;
- var prefixes = 'webkit moz ms o'.split(' ');
- // get unprefixed rAF and cAF, if present
- var requestAnimationFrame = window.requestAnimationFrame;
- var cancelAnimationFrame = window.cancelAnimationFrame;
- // loop through vendor prefixes and get prefixed rAF and cAF
- var prefix;
- for( var i = 0; i < prefixes.length; i++ ) {
- if ( requestAnimationFrame && cancelAnimationFrame ) {
- break;
- }
- prefix = prefixes[i];
- requestAnimationFrame = requestAnimationFrame || window[ prefix + 'RequestAnimationFrame' ];
- cancelAnimationFrame = cancelAnimationFrame || window[ prefix + 'CancelAnimationFrame' ] ||
- window[ prefix + 'CancelRequestAnimationFrame' ];
- }
- // fallback to setTimeout and clearTimeout if either request/cancel is not supported
- if ( !requestAnimationFrame || !cancelAnimationFrame ) {
- requestAnimationFrame = function( callback ) {
- var currTime = new Date().getTime();
- var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
- var id = window.setTimeout( function() {
- callback( currTime + timeToCall );
- }, timeToCall );
- lastTime = currTime + timeToCall;
- return id;
- };
- cancelAnimationFrame = function( id ) {
- window.clearTimeout( id );
- };
- }
- // -------------------------- animate -------------------------- //
- var proto = {};
- proto.startAnimation = function() {
- if ( this.isAnimating ) {
- return;
- }
- this.isAnimating = true;
- this.restingFrames = 0;
- this.animate();
- };
- proto.animate = function() {
- this.applyDragForce();
- this.applySelectedAttraction();
- var previousX = this.x;
- this.integratePhysics();
- this.positionSlider();
- this.settle( previousX );
- // animate next frame
- if ( this.isAnimating ) {
- var _this = this;
- requestAnimationFrame( function animateFrame() {
- _this.animate();
- });
- }
- /** /
- // log animation frame rate
- var now = new Date();
- if ( this.then ) {
- console.log( ~~( 1000 / (now-this.then)) + 'fps' )
- }
- this.then = now;
- /**/
- };
- var transformProperty = getStyleProperty('transform');
- var is3d = !!getStyleProperty('perspective');
- proto.positionSlider = function() {
- var x = this.x;
- // wrap position around
- if ( this.options.wrapAround && this.cells.length > 1 ) {
- x = utils.modulo( x, this.slideableWidth );
- x = x - this.slideableWidth;
- this.shiftWrapCells( x );
- }
- x = x + this.cursorPosition;
- // reverse if right-to-left and using transform
- x = this.options.rightToLeft && transformProperty ? -x : x;
- var value = this.getPositionValue( x );
- if ( transformProperty ) {
- // use 3D tranforms for hardware acceleration on iOS
- // but use 2D when settled, for better font-rendering
- this.slider.style[ transformProperty ] = is3d && this.isAnimating ?
- 'translate3d(' + value + ',0,0)' : 'translateX(' + value + ')';
- } else {
- this.slider.style[ this.originSide ] = value;
- }
- };
- proto.positionSliderAtSelected = function() {
- if ( !this.cells.length ) {
- return;
- }
- var selectedCell = this.cells[ this.selectedIndex ];
- this.x = -selectedCell.target;
- this.positionSlider();
- };
- proto.getPositionValue = function( position ) {
- if ( this.options.percentPosition ) {
- // percent position, round to 2 digits, like 12.34%
- return ( Math.round( ( position / this.size.innerWidth ) * 10000 ) * 0.01 )+ '%';
- } else {
- // pixel positioning
- return Math.round( position ) + 'px';
- }
- };
- proto.settle = function( previousX ) {
- // keep track of frames where x hasn't moved
- if ( !this.isPointerDown && Math.round( this.x * 100 ) == Math.round( previousX * 100 ) ) {
- this.restingFrames++;
- }
- // stop animating if resting for 3 or more frames
- if ( this.restingFrames > 2 ) {
- this.isAnimating = false;
- delete this.isFreeScrolling;
- // render position with translateX when settled
- if ( is3d ) {
- this.positionSlider();
- }
- this.dispatchEvent('settle');
- }
- };
- proto.shiftWrapCells = function( x ) {
- // shift before cells
- var beforeGap = this.cursorPosition + x;
- this._shiftCells( this.beforeShiftCells, beforeGap, -1 );
- // shift after cells
- var afterGap = this.size.innerWidth - ( x + this.slideableWidth + this.cursorPosition );
- this._shiftCells( this.afterShiftCells, afterGap, 1 );
- };
- proto._shiftCells = function( cells, gap, shift ) {
- for ( var i=0, len = cells.length; i < len; i++ ) {
- var cell = cells[i];
- var cellShift = gap > 0 ? shift : 0;
- cell.wrapShift( cellShift );
- gap -= cell.size.outerWidth;
- }
- };
- proto._unshiftCells = function( cells ) {
- if ( !cells || !cells.length ) {
- return;
- }
- for ( var i=0, len = cells.length; i < len; i++ ) {
- cells[i].wrapShift( 0 );
- }
- };
- // -------------------------- physics -------------------------- //
- proto.integratePhysics = function() {
- this.velocity += this.accel;
- this.x += this.velocity;
- this.velocity *= this.getFrictionFactor();
- // reset acceleration
- this.accel = 0;
- };
- proto.applyForce = function( force ) {
- this.accel += force;
- };
- proto.getFrictionFactor = function() {
- return 1 - this.options[ this.isFreeScrolling ? 'freeScrollFriction' : 'friction' ];
- };
- proto.getRestingPosition = function() {
- // my thanks to Steven Wittens, who simplified this math greatly
- return this.x + this.velocity / ( 1 - this.getFrictionFactor() );
- };
- proto.applyDragForce = function() {
- if ( !this.isPointerDown ) {
- return;
- }
- // change the position to drag position by applying force
- var dragVelocity = this.dragX - this.x;
- var dragForce = dragVelocity - this.velocity;
- this.applyForce( dragForce );
- };
- proto.applySelectedAttraction = function() {
- // do not attract if pointer down or no cells
- var len = this.cells.length;
- if ( this.isPointerDown || this.isFreeScrolling || !len ) {
- return;
- }
- var cell = this.cells[ this.selectedIndex ];
- var wrap = this.options.wrapAround && len > 1 ?
- this.slideableWidth * Math.floor( this.selectedIndex / len ) : 0;
- var distance = ( cell.target + wrap ) * -1 - this.x;
- var force = distance * this.options.selectedAttraction;
- this.applyForce( force );
- };
- return proto;
- }));
- },{"desandro-get-style-property":4,"fizzy-ui-utils":8}],11:[function(require,module,exports){
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'get-size/get-size'
- ], function( getSize ) {
- return factory( window, getSize );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('get-size')
- );
- } else {
- // browser global
- window.Flickity = window.Flickity || {};
- window.Flickity.Cell = factory(
- window,
- window.getSize
- );
- }
- }( window, function factory( window, getSize ) {
- 'use strict';
- function Cell( elem, parent ) {
- this.element = elem;
- this.parent = parent;
- this.create();
- }
- var isIE8 = 'attachEvent' in window;
- Cell.prototype.create = function() {
- this.element.style.position = 'absolute';
- // IE8 prevent child from changing focus http://stackoverflow.com/a/17525223/182183
- if ( isIE8 ) {
- this.element.setAttribute( 'unselectable', 'on' );
- }
- this.x = 0;
- this.shift = 0;
- };
- Cell.prototype.destroy = function() {
- // reset style
- this.element.style.position = '';
- var side = this.parent.originSide;
- this.element.style[ side ] = '';
- };
- Cell.prototype.getSize = function() {
- this.size = getSize( this.element );
- };
- Cell.prototype.setPosition = function( x ) {
- this.x = x;
- this.setDefaultTarget();
- this.renderPosition( x );
- };
- Cell.prototype.setDefaultTarget = function() {
- var marginProperty = this.parent.originSide == 'left' ? 'marginLeft' : 'marginRight';
- this.target = this.x + this.size[ marginProperty ] +
- this.size.width * this.parent.cellAlign;
- };
- Cell.prototype.renderPosition = function( x ) {
- // render position of cell with in slider
- var side = this.parent.originSide;
- this.element.style[ side ] = this.parent.getPositionValue( x );
- };
- /**
- * @param {Integer} factor - 0, 1, or -1
- **/
- Cell.prototype.wrapShift = function( shift ) {
- this.shift = shift;
- this.renderPosition( this.x + this.parent.slideableWidth * shift );
- };
- Cell.prototype.remove = function() {
- this.element.parentNode.removeChild( this.element );
- };
- return Cell;
- }));
- },{"get-size":19}],12:[function(require,module,exports){
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'classie/classie',
- 'eventie/eventie',
- './flickity',
- 'unidragger/unidragger',
- 'fizzy-ui-utils/utils'
- ], function( classie, eventie, Flickity, Unidragger, utils ) {
- return factory( window, classie, eventie, Flickity, Unidragger, utils );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('desandro-classie'),
- require('eventie'),
- require('./flickity'),
- require('unidragger'),
- require('fizzy-ui-utils')
- );
- } else {
- // browser global
- window.Flickity = factory(
- window,
- window.classie,
- window.eventie,
- window.Flickity,
- window.Unidragger,
- window.fizzyUIUtils
- );
- }
- }( window, function factory( window, classie, eventie, Flickity, Unidragger, utils ) {
- 'use strict';
- // handle IE8 prevent default
- function preventDefaultEvent( event ) {
- if ( event.preventDefault ) {
- event.preventDefault();
- } else {
- event.returnValue = false;
- }
- }
- // ----- defaults ----- //
- utils.extend( Flickity.defaults, {
- draggable: true
- });
- // ----- create ----- //
- Flickity.createMethods.push('_createDrag');
- // -------------------------- drag prototype -------------------------- //
- utils.extend( Flickity.prototype, Unidragger.prototype );
- // -------------------------- -------------------------- //
- Flickity.prototype._createDrag = function() {
- this.on( 'activate', this.bindDrag );
- this.on( 'uiChange', this._uiChangeDrag );
- this.on( 'childUIPointerDown', this._childUIPointerDownDrag );
- this.on( 'deactivate', this.unbindDrag );
- };
- Flickity.prototype.bindDrag = function() {
- if ( !this.options.draggable || this.isDragBound ) {
- return;
- }
- classie.add( this.element, 'is-draggable' );
- this.handles = [ this.viewport ];
- this.bindHandles();
- this.isDragBound = true;
- };
- Flickity.prototype.unbindDrag = function() {
- if ( !this.isDragBound ) {
- return;
- }
- classie.remove( this.element, 'is-draggable' );
- this.unbindHandles();
- delete this.isDragBound;
- };
- Flickity.prototype._uiChangeDrag = function() {
- delete this.isFreeScrolling;
- };
- Flickity.prototype._childUIPointerDownDrag = function( event ) {
- preventDefaultEvent( event );
- this.pointerDownFocus( event );
- };
- // -------------------------- pointer events -------------------------- //
- Flickity.prototype.pointerDown = function( event, pointer ) {
- // dismiss range sliders
- if ( event.target.nodeName == 'INPUT' && event.target.type == 'range' ) {
- // reset pointerDown logic
- this.isPointerDown = false;
- delete this.pointerIdentifier;
- return;
- }
- this._dragPointerDown( event, pointer );
- // kludge to blur focused inputs in dragger
- var focused = document.activeElement;
- if ( focused && focused.blur && focused != this.element &&
- // do not blur body for IE9 & 10, #117
- focused != document.body ) {
- focused.blur();
- }
- this.pointerDownFocus( event );
- // stop if it was moving
- this.dragX = this.x;
- classie.add( this.viewport, 'is-pointer-down' );
- // bind move and end events
- this._bindPostStartEvents( event );
- // track scrolling
- this.pointerDownScroll = Unidragger.getScrollPosition();
- eventie.bind( window, 'scroll', this );
- this.dispatchEvent( 'pointerDown', event, [ pointer ] );
- };
- var touchStartEvents = {
- touchstart: true,
- MSPointerDown: true
- };
- var focusNodes = {
- INPUT: true,
- SELECT: true
- };
- Flickity.prototype.pointerDownFocus = function( event ) {
- // focus element, if not touch, and its not an input or select
- if ( !this.options.accessibility || touchStartEvents[ event.type ] ||
- focusNodes[ event.target.nodeName ] ) {
- return;
- }
- var prevScrollY = window.pageYOffset;
- this.element.focus();
- // hack to fix scroll jump after focus, #76
- if ( window.pageYOffset != prevScrollY ) {
- window.scrollTo( window.pageXOffset, prevScrollY );
- }
- };
- // ----- move ----- //
- Flickity.prototype.hasDragStarted = function( moveVector ) {
- return Math.abs( moveVector.x ) > 3;
- };
- // ----- up ----- //
- Flickity.prototype.pointerUp = function( event, pointer ) {
- classie.remove( this.viewport, 'is-pointer-down' );
- this.dispatchEvent( 'pointerUp', event, [ pointer ] );
- this._dragPointerUp( event, pointer );
- };
- Flickity.prototype.pointerDone = function() {
- eventie.unbind( window, 'scroll', this );
- delete this.pointerDownScroll;
- };
- // -------------------------- dragging -------------------------- //
- Flickity.prototype.dragStart = function( event, pointer ) {
- this.dragStartPosition = this.x;
- this.startAnimation();
- this.dispatchEvent( 'dragStart', event, [ pointer ] );
- };
- Flickity.prototype.dragMove = function( event, pointer, moveVector ) {
- preventDefaultEvent( event );
- this.previousDragX = this.dragX;
- // reverse if right-to-left
- var direction = this.options.rightToLeft ? -1 : 1;
- var dragX = this.dragStartPosition + moveVector.x * direction;
- if ( !this.options.wrapAround && this.cells.length ) {
- // slow drag
- var originBound = Math.max( -this.cells[0].target, this.dragStartPosition );
- dragX = dragX > originBound ? ( dragX + originBound ) * 0.5 : dragX;
- var endBound = Math.min( -this.getLastCell().target, this.dragStartPosition );
- dragX = dragX < endBound ? ( dragX + endBound ) * 0.5 : dragX;
- }
- this.dragX = dragX;
- this.dragMoveTime = new Date();
- this.dispatchEvent( 'dragMove', event, [ pointer, moveVector ] );
- };
- Flickity.prototype.dragEnd = function( event, pointer ) {
- if ( this.options.freeScroll ) {
- this.isFreeScrolling = true;
- }
- // set selectedIndex based on where flick will end up
- var index = this.dragEndRestingSelect();
- if ( this.options.freeScroll && !this.options.wrapAround ) {
- // if free-scroll & not wrap around
- // do not free-scroll if going outside of bounding cells
- // so bounding cells can attract slider, and keep it in bounds
- var restingX = this.getRestingPosition();
- this.isFreeScrolling = -restingX > this.cells[0].target &&
- -restingX < this.getLastCell().target;
- } else if ( !this.options.freeScroll && index == this.selectedIndex ) {
- // boost selection if selected index has not changed
- index += this.dragEndBoostSelect();
- }
- delete this.previousDragX;
- // apply selection
- // TODO refactor this, selecting here feels weird
- this.select( index );
- this.dispatchEvent( 'dragEnd', event, [ pointer ] );
- };
- Flickity.prototype.dragEndRestingSelect = function() {
- var restingX = this.getRestingPosition();
- // how far away from selected cell
- var distance = Math.abs( this.getCellDistance( -restingX, this.selectedIndex ) );
- // get closet resting going up and going down
- var positiveResting = this._getClosestResting( restingX, distance, 1 );
- var negativeResting = this._getClosestResting( restingX, distance, -1 );
- // use closer resting for wrap-around
- var index = positiveResting.distance < negativeResting.distance ?
- positiveResting.index : negativeResting.index;
- return index;
- };
- /**
- * given resting X and distance to selected cell
- * get the distance and index of the closest cell
- * @param {Number} restingX - estimated post-flick resting position
- * @param {Number} distance - distance to selected cell
- * @param {Integer} increment - +1 or -1, going up or down
- * @returns {Object} - { distance: {Number}, index: {Integer} }
- */
- Flickity.prototype._getClosestResting = function( restingX, distance, increment ) {
- var index = this.selectedIndex;
- var minDistance = Infinity;
- var condition = this.options.contain && !this.options.wrapAround ?
- // if contain, keep going if distance is equal to minDistance
- function( d, md ) { return d <= md; } : function( d, md ) { return d < md; };
- while ( condition( distance, minDistance ) ) {
- // measure distance to next cell
- index += increment;
- minDistance = distance;
- distance = this.getCellDistance( -restingX, index );
- if ( distance === null ) {
- break;
- }
- distance = Math.abs( distance );
- }
- return {
- distance: minDistance,
- // selected was previous index
- index: index - increment
- };
- };
- /**
- * measure distance between x and a cell target
- * @param {Number} x
- * @param {Integer} index - cell index
- */
- Flickity.prototype.getCellDistance = function( x, index ) {
- var len = this.cells.length;
- // wrap around if at least 2 cells
- var isWrapAround = this.options.wrapAround && len > 1;
- var cellIndex = isWrapAround ? utils.modulo( index, len ) : index;
- var cell = this.cells[ cellIndex ];
- if ( !cell ) {
- return null;
- }
- // add distance for wrap-around cells
- var wrap = isWrapAround ? this.slideableWidth * Math.floor( index / len ) : 0;
- return x - ( cell.target + wrap );
- };
- Flickity.prototype.dragEndBoostSelect = function() {
- // do not boost if no previousDragX or dragMoveTime
- if ( this.previousDragX === undefined || !this.dragMoveTime ||
- // or if drag was held for 100 ms
- new Date() - this.dragMoveTime > 100 ) {
- return 0;
- }
- var distance = this.getCellDistance( -this.dragX, this.selectedIndex );
- var delta = this.previousDragX - this.dragX;
- if ( distance > 0 && delta > 0 ) {
- // boost to next if moving towards the right, and positive velocity
- return 1;
- } else if ( distance < 0 && delta < 0 ) {
- // boost to previous if moving towards the left, and negative velocity
- return -1;
- }
- return 0;
- };
- // ----- staticClick ----- //
- Flickity.prototype.staticClick = function( event, pointer ) {
- // get clickedCell, if cell was clicked
- var clickedCell = this.getParentCell( event.target );
- var cellElem = clickedCell && clickedCell.element;
- var cellIndex = clickedCell && utils.indexOf( this.cells, clickedCell );
- this.dispatchEvent( 'staticClick', event, [ pointer, cellElem, cellIndex ] );
- };
- // ----- ----- //
- return Flickity;
- }));
- },{"./flickity":13,"desandro-classie":3,"eventie":7,"fizzy-ui-utils":8,"unidragger":22}],13:[function(require,module,exports){
- /**
- * Flickity main
- */
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'classie/classie',
- 'eventEmitter/EventEmitter',
- 'eventie/eventie',
- 'get-size/get-size',
- 'fizzy-ui-utils/utils',
- './cell',
- './animate'
- ], function( classie, EventEmitter, eventie, getSize, utils, Cell, animatePrototype ) {
- return factory( window, classie, EventEmitter, eventie, getSize, utils, Cell, animatePrototype );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('desandro-classie'),
- require('wolfy87-eventemitter'),
- require('eventie'),
- require('get-size'),
- require('fizzy-ui-utils'),
- require('./cell'),
- require('./animate')
- );
- } else {
- // browser global
- var _Flickity = window.Flickity;
- window.Flickity = factory(
- window,
- window.classie,
- window.EventEmitter,
- window.eventie,
- window.getSize,
- window.fizzyUIUtils,
- _Flickity.Cell,
- _Flickity.animatePrototype
- );
- }
- }( window, function factory( window, classie, EventEmitter, eventie, getSize,
- utils, Cell, animatePrototype ) {
- 'use strict';
- // vars
- var jQuery = window.jQuery;
- var getComputedStyle = window.getComputedStyle;
- var console = window.console;
- function moveElements( elems, toElem ) {
- elems = utils.makeArray( elems );
- while ( elems.length ) {
- toElem.appendChild( elems.shift() );
- }
- }
- // -------------------------- Flickity -------------------------- //
- // globally unique identifiers
- var GUID = 0;
- // internal store of all Flickity intances
- var instances = {};
- function Flickity( element, options ) {
- var queryElement = utils.getQueryElement( element );
- if ( !queryElement ) {
- if ( console ) {
- console.error( 'Bad element for Flickity: ' + ( queryElement || element ) );
- }
- return;
- }
- this.element = queryElement;
- // add jQuery
- if ( jQuery ) {
- this.$element = jQuery( this.element );
- }
- // options
- this.options = utils.extend( {}, this.constructor.defaults );
- this.option( options );
- // kick things off
- this._create();
- }
- Flickity.defaults = {
- accessibility: true,
- cellAlign: 'center',
- // cellSelector: undefined,
- // contain: false,
- freeScrollFriction: 0.075, // friction when free-scrolling
- friction: 0.28, // friction when selecting
- // initialIndex: 0,
- percentPosition: true,
- resize: true,
- selectedAttraction: 0.025,
- setGallerySize: true
- // watchCSS: false,
- // wrapAround: false
- };
- // hash of methods triggered on _create()
- Flickity.createMethods = [];
- // inherit EventEmitter
- utils.extend( Flickity.prototype, EventEmitter.prototype );
- Flickity.prototype._create = function() {
- // add id for Flickity.data
- var id = this.guid = ++GUID;
- this.element.flickityGUID = id; // expando
- instances[ id ] = this; // associate via id
- // initial properties
- this.selectedIndex = 0;
- // how many frames slider has been in same position
- this.restingFrames = 0;
- // initial physics properties
- this.x = 0;
- this.velocity = 0;
- this.accel = 0;
- this.originSide = this.options.rightToLeft ? 'right' : 'left';
- // create viewport & slider
- this.viewport = document.createElement('div');
- this.viewport.className = 'flickity-viewport';
- Flickity.setUnselectable( this.viewport );
- this._createSlider();
- if ( this.options.resize || this.options.watchCSS ) {
- eventie.bind( window, 'resize', this );
- this.isResizeBound = true;
- }
- for ( var i=0, len = Flickity.createMethods.length; i < len; i++ ) {
- var method = Flickity.createMethods[i];
- this[ method ]();
- }
- if ( this.options.watchCSS ) {
- this.watchCSS();
- } else {
- this.activate();
- }
- };
- /**
- * set options
- * @param {Object} opts
- */
- Flickity.prototype.option = function( opts ) {
- utils.extend( this.options, opts );
- };
- Flickity.prototype.activate = function() {
- if ( this.isActive ) {
- return;
- }
- this.isActive = true;
- classie.add( this.element, 'flickity-enabled' );
- if ( this.options.rightToLeft ) {
- classie.add( this.element, 'flickity-rtl' );
- }
- this.getSize();
- // move initial cell elements so they can be loaded as cells
- var cellElems = this._filterFindCellElements( this.element.children );
- moveElements( cellElems, this.slider );
- this.viewport.appendChild( this.slider );
- this.element.appendChild( this.viewport );
- // get cells from children
- this.reloadCells();
- if ( this.options.accessibility ) {
- // allow element to focusable
- this.element.tabIndex = 0;
- // listen for key presses
- eventie.bind( this.element, 'keydown', this );
- }
- this.emit('activate');
- var index;
- var initialIndex = this.options.initialIndex;
- if ( this.isInitActivated ) {
- index = this.selectedIndex;
- } else if ( initialIndex !== undefined ) {
- index = this.cells[ initialIndex ] ? initialIndex : 0;
- } else {
- index = 0;
- }
- // select instantly
- this.select( index, false, true );
- // flag for initial activation, for using initialIndex
- this.isInitActivated = true;
- };
- // slider positions the cells
- Flickity.prototype._createSlider = function() {
- // slider element does all the positioning
- var slider = document.createElement('div');
- slider.className = 'flickity-slider';
- slider.style[ this.originSide ] = 0;
- this.slider = slider;
- };
- Flickity.prototype._filterFindCellElements = function( elems ) {
- return utils.filterFindElements( elems, this.options.cellSelector );
- };
- // goes through all children
- Flickity.prototype.reloadCells = function() {
- // collection of item elements
- this.cells = this._makeCells( this.slider.children );
- this.positionCells();
- this._getWrapShiftCells();
- this.setGallerySize();
- };
- /**
- * turn elements into Flickity.Cells
- * @param {Array or NodeList or HTMLElement} elems
- * @returns {Array} items - collection of new Flickity Cells
- */
- Flickity.prototype._makeCells = function( elems ) {
- var cellElems = this._filterFindCellElements( elems );
- // create new Flickity for collection
- var cells = [];
- for ( var i=0, len = cellElems.length; i < len; i++ ) {
- var elem = cellElems[i];
- var cell = new Cell( elem, this );
- cells.push( cell );
- }
- return cells;
- };
- Flickity.prototype.getLastCell = function() {
- return this.cells[ this.cells.length - 1 ];
- };
- // positions all cells
- Flickity.prototype.positionCells = function() {
- // size all cells
- this._sizeCells( this.cells );
- // position all cells
- this._positionCells( 0 );
- };
- /**
- * position certain cells
- * @param {Integer} index - which cell to start with
- */
- Flickity.prototype._positionCells = function( index ) {
- index = index || 0;
- // also measure maxCellHeight
- // start 0 if positioning all cells
- this.maxCellHeight = index ? this.maxCellHeight || 0 : 0;
- var cellX = 0;
- // get cellX
- if ( index > 0 ) {
- var startCell = this.cells[ index - 1 ];
- cellX = startCell.x + startCell.size.outerWidth;
- }
- var cell;
- for ( var len = this.cells.length, i=index; i < len; i++ ) {
- cell = this.cells[i];
- cell.setPosition( cellX );
- cellX += cell.size.outerWidth;
- this.maxCellHeight = Math.max( cell.size.outerHeight, this.maxCellHeight );
- }
- // keep track of cellX for wrap-around
- this.slideableWidth = cellX;
- // contain cell target
- this._containCells();
- };
- /**
- * cell.getSize() on multiple cells
- * @param {Array} cells
- */
- Flickity.prototype._sizeCells = function( cells ) {
- for ( var i=0, len = cells.length; i < len; i++ ) {
- var cell = cells[i];
- cell.getSize();
- }
- };
- // alias _init for jQuery plugin .flickity()
- Flickity.prototype._init =
- Flickity.prototype.reposition = function() {
- this.positionCells();
- this.positionSliderAtSelected();
- };
- Flickity.prototype.getSize = function() {
- this.size = getSize( this.element );
- this.setCellAlign();
- this.cursorPosition = this.size.innerWidth * this.cellAlign;
- };
- var cellAlignShorthands = {
- // cell align, then based on origin side
- center: {
- left: 0.5,
- right: 0.5
- },
- left: {
- left: 0,
- right: 1
- },
- right: {
- right: 0,
- left: 1
- }
- };
- Flickity.prototype.setCellAlign = function() {
- var shorthand = cellAlignShorthands[ this.options.cellAlign ];
- this.cellAlign = shorthand ? shorthand[ this.originSide ] : this.options.cellAlign;
- };
- Flickity.prototype.setGallerySize = function() {
- if ( this.options.setGallerySize ) {
- this.viewport.style.height = this.maxCellHeight + 'px';
- }
- };
- Flickity.prototype._getWrapShiftCells = function() {
- // only for wrap-around
- if ( !this.options.wrapAround ) {
- return;
- }
- // unshift previous cells
- this._unshiftCells( this.beforeShiftCells );
- this._unshiftCells( this.afterShiftCells );
- // get before cells
- // initial gap
- var gapX = this.cursorPosition;
- var cellIndex = this.cells.length - 1;
- this.beforeShiftCells = this._getGapCells( gapX, cellIndex, -1 );
- // get after cells
- // ending gap between last cell and end of gallery viewport
- gapX = this.size.innerWidth - this.cursorPosition;
- // start cloning at first cell, working forwards
- this.afterShiftCells = this._getGapCells( gapX, 0, 1 );
- };
- Flickity.prototype._getGapCells = function( gapX, cellIndex, increment ) {
- // keep adding cells until the cover the initial gap
- var cells = [];
- while ( gapX > 0 ) {
- var cell = this.cells[ cellIndex ];
- if ( !cell ) {
- break;
- }
- cells.push( cell );
- cellIndex += increment;
- gapX -= cell.size.outerWidth;
- }
- return cells;
- };
- // ----- contain ----- //
- // contain cell targets so no excess sliding
- Flickity.prototype._containCells = function() {
- if ( !this.options.contain || this.options.wrapAround || !this.cells.length ) {
- return;
- }
- var startMargin = this.options.rightToLeft ? 'marginRight' : 'marginLeft';
- var endMargin = this.options.rightToLeft ? 'marginLeft' : 'marginRight';
- var firstCellStartMargin = this.cells[0].size[ startMargin ];
- var lastCell = this.getLastCell();
- var contentWidth = this.slideableWidth - lastCell.size[ endMargin ];
- var endLimit = contentWidth - this.size.innerWidth * ( 1 - this.cellAlign );
- // content is less than gallery size
- var isContentSmaller = contentWidth < this.size.innerWidth;
- // contain each cell target
- for ( var i=0, len = this.cells.length; i < len; i++ ) {
- var cell = this.cells[i];
- // reset default target
- cell.setDefaultTarget();
- if ( isContentSmaller ) {
- // all cells fit inside gallery
- cell.target = contentWidth * this.cellAlign;
- } else {
- // contain to bounds
- cell.target = Math.max( cell.target, this.cursorPosition + firstCellStartMargin );
- cell.target = Math.min( cell.target, endLimit );
- }
- }
- };
- // ----- ----- //
- /**
- * emits events via eventEmitter and jQuery events
- * @param {String} type - name of event
- * @param {Event} event - original event
- * @param {Array} args - extra arguments
- */
- Flickity.prototype.dispatchEvent = function( type, event, args ) {
- var emitArgs = [ event ].concat( args );
- this.emitEvent( type, emitArgs );
- if ( jQuery && this.$element ) {
- if ( event ) {
- // create jQuery event
- var $event = jQuery.Event( event );
- $event.type = type;
- this.$element.trigger( $event, args );
- } else {
- // just trigger with type if no event available
- this.$element.trigger( type, args );
- }
- }
- };
- // -------------------------- select -------------------------- //
- /**
- * @param {Integer} index - index of the cell
- * @param {Boolean} isWrap - will wrap-around to last/first if at the end
- * @param {Boolean} isInstant - will immediately set position at selected cell
- */
- Flickity.prototype.select = function( index, isWrap, isInstant ) {
- if ( !this.isActive ) {
- return;
- }
- index = parseInt( index, 10 );
- // wrap position so slider is within normal area
- var len = this.cells.length;
- if ( this.options.wrapAround && len > 1 ) {
- if ( index < 0 ) {
- this.x -= this.slideableWidth;
- } else if ( index >= len ) {
- this.x += this.slideableWidth;
- }
- }
- if ( this.options.wrapAround || isWrap ) {
- index = utils.modulo( index, len );
- }
- // bail if invalid index
- if ( !this.cells[ index ] ) {
- return;
- }
- this.selectedIndex = index;
- this.setSelectedCell();
- if ( isInstant ) {
- this.positionSliderAtSelected();
- } else {
- this.startAnimation();
- }
- this.dispatchEvent('cellSelect');
- };
- Flickity.prototype.previous = function( isWrap ) {
- this.select( this.selectedIndex - 1, isWrap );
- };
- Flickity.prototype.next = function( isWrap ) {
- this.select( this.selectedIndex + 1, isWrap );
- };
- Flickity.prototype.setSelectedCell = function() {
- this._removeSelectedCellClass();
- this.selectedCell = this.cells[ this.selectedIndex ];
- this.selectedElement = this.selectedCell.element;
- classie.add( this.selectedElement, 'is-selected' );
- };
- Flickity.prototype._removeSelectedCellClass = function() {
- if ( this.selectedCell ) {
- classie.remove( this.selectedCell.element, 'is-selected' );
- }
- };
- // -------------------------- get cells -------------------------- //
- /**
- * get Flickity.Cell, given an Element
- * @param {Element} elem
- * @returns {Flickity.Cell} item
- */
- Flickity.prototype.getCell = function( elem ) {
- // loop through cells to get the one that matches
- for ( var i=0, len = this.cells.length; i < len; i++ ) {
- var cell = this.cells[i];
- if ( cell.element == elem ) {
- return cell;
- }
- }
- };
- /**
- * get collection of Flickity.Cells, given Elements
- * @param {Element, Array, NodeList} elems
- * @returns {Array} cells - Flickity.Cells
- */
- Flickity.prototype.getCells = function( elems ) {
- elems = utils.makeArray( elems );
- var cells = [];
- for ( var i=0, len = elems.length; i < len; i++ ) {
- var elem = elems[i];
- var cell = this.getCell( elem );
- if ( cell ) {
- cells.push( cell );
- }
- }
- return cells;
- };
- /**
- * get cell elements
- * @returns {Array} cellElems
- */
- Flickity.prototype.getCellElements = function() {
- var cellElems = [];
- for ( var i=0, len = this.cells.length; i < len; i++ ) {
- cellElems.push( this.cells[i].element );
- }
- return cellElems;
- };
- /**
- * get parent cell from an element
- * @param {Element} elem
- * @returns {Flickit.Cell} cell
- */
- Flickity.prototype.getParentCell = function( elem ) {
- // first check if elem is cell
- var cell = this.getCell( elem );
- if ( cell ) {
- return cell;
- }
- // try to get parent cell elem
- elem = utils.getParent( elem, '.flickity-slider > *' );
- return this.getCell( elem );
- };
- /**
- * get cells adjacent to a cell
- * @param {Integer} adjCount - number of adjacent cells
- * @param {Integer} index - index of cell to start
- * @returns {Array} cells - array of Flickity.Cells
- */
- Flickity.prototype.getAdjacentCellElements = function( adjCount, index ) {
- if ( !adjCount ) {
- return [ this.selectedElement ];
- }
- index = index === undefined ? this.selectedIndex : index;
- var len = this.cells.length;
- if ( 1 + ( adjCount * 2 ) >= len ) {
- return this.getCellElements();
- }
- var cellElems = [];
- for ( var i = index - adjCount; i <= index + adjCount ; i++ ) {
- var cellIndex = this.options.wrapAround ? utils.modulo( i, len ) : i;
- var cell = this.cells[ cellIndex ];
- if ( cell ) {
- cellElems.push( cell.element );
- }
- }
- return cellElems;
- };
- // -------------------------- events -------------------------- //
- Flickity.prototype.uiChange = function() {
- this.emit('uiChange');
- };
- Flickity.prototype.childUIPointerDown = function( event ) {
- this.emitEvent( 'childUIPointerDown', [ event ] );
- };
- // ----- resize ----- //
- Flickity.prototype.onresize = function() {
- this.watchCSS();
- this.resize();
- };
- utils.debounceMethod( Flickity, 'onresize', 150 );
- Flickity.prototype.resize = function() {
- if ( !this.isActive ) {
- return;
- }
- this.getSize();
- // wrap values
- if ( this.options.wrapAround ) {
- this.x = utils.modulo( this.x, this.slideableWidth );
- }
- this.positionCells();
- this._getWrapShiftCells();
- this.setGallerySize();
- this.positionSliderAtSelected();
- };
- var supportsConditionalCSS = Flickity.supportsConditionalCSS = ( function() {
- var supports;
- return function checkSupport() {
- if ( supports !== undefined ) {
- return supports;
- }
- if ( !getComputedStyle ) {
- supports = false;
- return;
- }
- // style body's :after and check that
- var style = document.createElement('style');
- var cssText = document.createTextNode('body:after { content: "foo"; display: none; }');
- style.appendChild( cssText );
- document.head.appendChild( style );
- var afterContent = getComputedStyle( document.body, ':after' ).content;
- // check if able to get :after content
- supports = afterContent.indexOf('foo') != -1;
- document.head.removeChild( style );
- return supports;
- };
- })();
- // watches the :after property, activates/deactivates
- Flickity.prototype.watchCSS = function() {
- var watchOption = this.options.watchCSS;
- if ( !watchOption ) {
- return;
- }
- var supports = supportsConditionalCSS();
- if ( !supports ) {
- // activate if watch option is fallbackOn
- var method = watchOption == 'fallbackOn' ? 'activate' : 'deactivate';
- this[ method ]();
- return;
- }
- var afterContent = getComputedStyle( this.element, ':after' ).content;
- // activate if :after { content: 'flickity' }
- if ( afterContent.indexOf('flickity') != -1 ) {
- this.activate();
- } else {
- this.deactivate();
- }
- };
- // ----- keydown ----- //
- // go previous/next if left/right keys pressed
- Flickity.prototype.onkeydown = function( event ) {
- // only work if element is in focus
- if ( !this.options.accessibility ||
- ( document.activeElement && document.activeElement != this.element ) ) {
- return;
- }
- if ( event.keyCode == 37 ) {
- // go left
- var leftMethod = this.options.rightToLeft ? 'next' : 'previous';
- this.uiChange();
- this[ leftMethod ]();
- } else if ( event.keyCode == 39 ) {
- // go right
- var rightMethod = this.options.rightToLeft ? 'previous' : 'next';
- this.uiChange();
- this[ rightMethod ]();
- }
- };
- // -------------------------- destroy -------------------------- //
- // deactivate all Flickity functionality, but keep stuff available
- Flickity.prototype.deactivate = function() {
- if ( !this.isActive ) {
- return;
- }
- classie.remove( this.element, 'flickity-enabled' );
- classie.remove( this.element, 'flickity-rtl' );
- // destroy cells
- for ( var i=0, len = this.cells.length; i < len; i++ ) {
- var cell = this.cells[i];
- cell.destroy();
- }
- this._removeSelectedCellClass();
- this.element.removeChild( this.viewport );
- // move child elements back into element
- moveElements( this.slider.children, this.element );
- if ( this.options.accessibility ) {
- this.element.removeAttribute('tabIndex');
- eventie.unbind( this.element, 'keydown', this );
- }
- // set flags
- this.isActive = false;
- this.emit('deactivate');
- };
- Flickity.prototype.destroy = function() {
- this.deactivate();
- if ( this.isResizeBound ) {
- eventie.unbind( window, 'resize', this );
- }
- this.emit('destroy');
- if ( jQuery && this.$element ) {
- jQuery.removeData( this.element, 'flickity' );
- }
- delete this.element.flickityGUID;
- delete instances[ this.guid ];
- };
- // -------------------------- prototype -------------------------- //
- utils.extend( Flickity.prototype, animatePrototype );
- // -------------------------- extras -------------------------- //
- // quick check for IE8
- var isIE8 = 'attachEvent' in window;
- Flickity.setUnselectable = function( elem ) {
- if ( !isIE8 ) {
- return;
- }
- // IE8 prevent child from changing focus http://stackoverflow.com/a/17525223/182183
- elem.setAttribute( 'unselectable', 'on' );
- };
- /**
- * get Flickity instance from element
- * @param {Element} elem
- * @returns {Flickity}
- */
- Flickity.data = function( elem ) {
- elem = utils.getQueryElement( elem );
- var id = elem && elem.flickityGUID;
- return id && instances[ id ];
- };
- utils.htmlInit( Flickity, 'flickity' );
- if ( jQuery && jQuery.bridget ) {
- jQuery.bridget( 'flickity', Flickity );
- }
- Flickity.Cell = Cell;
- return Flickity;
- }));
- },{"./animate":10,"./cell":11,"desandro-classie":3,"eventie":7,"fizzy-ui-utils":8,"get-size":19,"wolfy87-eventemitter":24}],14:[function(require,module,exports){
- /*!
- * Flickity v1.2.1
- * Touch, responsive, flickable galleries
- *
- * Licensed GPLv3 for open source use
- * or Flickity Commercial License for commercial use
- *
- * http://flickity.metafizzy.co
- * Copyright 2015 Metafizzy
- */
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- './flickity',
- './drag',
- './prev-next-button',
- './page-dots',
- './player',
- './add-remove-cell',
- './lazyload'
- ], factory );
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- require('./flickity'),
- require('./drag'),
- require('./prev-next-button'),
- require('./page-dots'),
- require('./player'),
- require('./add-remove-cell'),
- require('./lazyload')
- );
- }
- })( window, function factory( Flickity ) {
- /*jshint strict: false*/
- return Flickity;
- });
- },{"./add-remove-cell":9,"./drag":12,"./flickity":13,"./lazyload":15,"./page-dots":16,"./player":17,"./prev-next-button":18}],15:[function(require,module,exports){
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'classie/classie',
- 'eventie/eventie',
- './flickity',
- 'fizzy-ui-utils/utils'
- ], function( classie, eventie, Flickity, utils ) {
- return factory( window, classie, eventie, Flickity, utils );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('desandro-classie'),
- require('eventie'),
- require('./flickity'),
- require('fizzy-ui-utils')
- );
- } else {
- // browser global
- factory(
- window,
- window.classie,
- window.eventie,
- window.Flickity,
- window.fizzyUIUtils
- );
- }
- }( window, function factory( window, classie, eventie, Flickity, utils ) {
- 'use strict';
- Flickity.createMethods.push('_createLazyload');
- Flickity.prototype._createLazyload = function() {
- this.on( 'cellSelect', this.lazyLoad );
- };
- Flickity.prototype.lazyLoad = function() {
- var lazyLoad = this.options.lazyLoad;
- if ( !lazyLoad ) {
- return;
- }
- // get adjacent cells, use lazyLoad option for adjacent count
- var adjCount = typeof lazyLoad == 'number' ? lazyLoad : 0;
- var cellElems = this.getAdjacentCellElements( adjCount );
- // get lazy images in those cells
- var lazyImages = [];
- for ( var i=0, len = cellElems.length; i < len; i++ ) {
- var cellElem = cellElems[i];
- var lazyCellImages = getCellLazyImages( cellElem );
- lazyImages = lazyImages.concat( lazyCellImages );
- }
- // load lazy images
- for ( i=0, len = lazyImages.length; i < len; i++ ) {
- var img = lazyImages[i];
- new LazyLoader( img, this );
- }
- };
- function getCellLazyImages( cellElem ) {
- // check if cell element is lazy image
- if ( cellElem.nodeName == 'IMG' &&
- cellElem.getAttribute('data-flickity-lazyload') ) {
- return [ cellElem ];
- }
- // select lazy images in cell
- var imgs = cellElem.querySelectorAll('img[data-flickity-lazyload]');
- return utils.makeArray( imgs );
- }
- // -------------------------- LazyLoader -------------------------- //
- /**
- * class to handle loading images
- */
- function LazyLoader( img, flickity ) {
- this.img = img;
- this.flickity = flickity;
- this.load();
- }
- LazyLoader.prototype.handleEvent = utils.handleEvent;
- LazyLoader.prototype.load = function() {
- eventie.bind( this.img, 'load', this );
- eventie.bind( this.img, 'error', this );
- // load image
- this.img.src = this.img.getAttribute('data-flickity-lazyload');
- // remove attr
- this.img.removeAttribute('data-flickity-lazyload');
- };
- LazyLoader.prototype.onload = function( event ) {
- this.complete( event, 'flickity-lazyloaded' );
- };
- LazyLoader.prototype.onerror = function( event ) {
- this.complete( event, 'flickity-lazyerror' );
- };
- LazyLoader.prototype.complete = function( event, className ) {
- // unbind events
- eventie.unbind( this.img, 'load', this );
- eventie.unbind( this.img, 'error', this );
- var cell = this.flickity.getParentCell( this.img );
- var cellElem = cell && cell.element;
- this.flickity.cellSizeChange( cellElem );
- classie.add( this.img, className );
- this.flickity.dispatchEvent( 'lazyLoad', event, cellElem );
- };
- // ----- ----- //
- Flickity.LazyLoader = LazyLoader;
- return Flickity;
- }));
- },{"./flickity":13,"desandro-classie":3,"eventie":7,"fizzy-ui-utils":8}],16:[function(require,module,exports){
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'eventie/eventie',
- './flickity',
- 'tap-listener/tap-listener',
- 'fizzy-ui-utils/utils'
- ], function( eventie, Flickity, TapListener, utils ) {
- return factory( window, eventie, Flickity, TapListener, utils );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('eventie'),
- require('./flickity'),
- require('tap-listener'),
- require('fizzy-ui-utils')
- );
- } else {
- // browser global
- factory(
- window,
- window.eventie,
- window.Flickity,
- window.TapListener,
- window.fizzyUIUtils
- );
- }
- }( window, function factory( window, eventie, Flickity, TapListener, utils ) {
- // -------------------------- PageDots -------------------------- //
- 'use strict';
- function PageDots( parent ) {
- this.parent = parent;
- this._create();
- }
- PageDots.prototype = new TapListener();
- PageDots.prototype._create = function() {
- // create holder element
- this.holder = document.createElement('ol');
- this.holder.className = 'flickity-page-dots';
- Flickity.setUnselectable( this.holder );
- // create dots, array of elements
- this.dots = [];
- // update on select
- var _this = this;
- this.onCellSelect = function() {
- _this.updateSelected();
- };
- this.parent.on( 'cellSelect', this.onCellSelect );
- // tap
- this.on( 'tap', this.onTap );
- // pointerDown
- this.on( 'pointerDown', function onPointerDown( button, event ) {
- _this.parent.childUIPointerDown( event );
- });
- };
- PageDots.prototype.activate = function() {
- this.setDots();
- this.bindTap( this.holder );
- // add to DOM
- this.parent.element.appendChild( this.holder );
- };
- PageDots.prototype.deactivate = function() {
- // remove from DOM
- this.parent.element.removeChild( this.holder );
- TapListener.prototype.destroy.call( this );
- };
- PageDots.prototype.setDots = function() {
- // get difference between number of cells and number of dots
- var delta = this.parent.cells.length - this.dots.length;
- if ( delta > 0 ) {
- this.addDots( delta );
- } else if ( delta < 0 ) {
- this.removeDots( -delta );
- }
- };
- PageDots.prototype.addDots = function( count ) {
- var fragment = document.createDocumentFragment();
- var newDots = [];
- while ( count ) {
- var dot = document.createElement('li');
- dot.className = 'dot';
- fragment.appendChild( dot );
- newDots.push( dot );
- count--;
- }
- this.holder.appendChild( fragment );
- this.dots = this.dots.concat( newDots );
- };
- PageDots.prototype.removeDots = function( count ) {
- // remove from this.dots collection
- var removeDots = this.dots.splice( this.dots.length - count, count );
- // remove from DOM
- for ( var i=0, len = removeDots.length; i < len; i++ ) {
- var dot = removeDots[i];
- this.holder.removeChild( dot );
- }
- };
- PageDots.prototype.updateSelected = function() {
- // remove selected class on previous
- if ( this.selectedDot ) {
- this.selectedDot.className = 'dot';
- }
- // don't proceed if no dots
- if ( !this.dots.length ) {
- return;
- }
- this.selectedDot = this.dots[ this.parent.selectedIndex ];
- this.selectedDot.className = 'dot is-selected';
- };
- PageDots.prototype.onTap = function( event ) {
- var target = event.target;
- // only care about dot clicks
- if ( target.nodeName != 'LI' ) {
- return;
- }
- this.parent.uiChange();
- var index = utils.indexOf( this.dots, target );
- this.parent.select( index );
- };
- PageDots.prototype.destroy = function() {
- this.deactivate();
- };
- Flickity.PageDots = PageDots;
- // -------------------------- Flickity -------------------------- //
- utils.extend( Flickity.defaults, {
- pageDots: true
- });
- Flickity.createMethods.push('_createPageDots');
- Flickity.prototype._createPageDots = function() {
- if ( !this.options.pageDots ) {
- return;
- }
- this.pageDots = new PageDots( this );
- this.on( 'activate', this.activatePageDots );
- this.on( 'cellAddedRemoved', this.onCellAddedRemovedPageDots );
- this.on( 'deactivate', this.deactivatePageDots );
- };
- Flickity.prototype.activatePageDots = function() {
- this.pageDots.activate();
- };
- Flickity.prototype.onCellAddedRemovedPageDots = function() {
- this.pageDots.setDots();
- };
- Flickity.prototype.deactivatePageDots = function() {
- this.pageDots.deactivate();
- };
- // ----- ----- //
- Flickity.PageDots = PageDots;
- return Flickity;
- }));
- },{"./flickity":13,"eventie":7,"fizzy-ui-utils":8,"tap-listener":21}],17:[function(require,module,exports){
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'eventEmitter/EventEmitter',
- 'eventie/eventie',
- 'fizzy-ui-utils/utils',
- './flickity'
- ], function( EventEmitter, eventie, utils, Flickity ) {
- return factory( EventEmitter, eventie, utils, Flickity );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- require('wolfy87-eventemitter'),
- require('eventie'),
- require('fizzy-ui-utils'),
- require('./flickity')
- );
- } else {
- // browser global
- factory(
- window.EventEmitter,
- window.eventie,
- window.fizzyUIUtils,
- window.Flickity
- );
- }
- }( window, function factory( EventEmitter, eventie, utils, Flickity ) {
- 'use strict';
- // -------------------------- Page Visibility -------------------------- //
- // https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API
- var hiddenProperty, visibilityEvent;
- if ( 'hidden' in document ) {
- hiddenProperty = 'hidden';
- visibilityEvent = 'visibilitychange';
- } else if ( 'webkitHidden' in document ) {
- hiddenProperty = 'webkitHidden';
- visibilityEvent = 'webkitvisibilitychange';
- }
- // -------------------------- Player -------------------------- //
- function Player( parent ) {
- this.parent = parent;
- this.state = 'stopped';
- // visibility change event handler
- if ( visibilityEvent ) {
- var _this = this;
- this.onVisibilityChange = function() {
- _this.visibilityChange();
- };
- }
- }
- Player.prototype = new EventEmitter();
- // start play
- Player.prototype.play = function() {
- if ( this.state == 'playing' ) {
- return;
- }
- this.state = 'playing';
- // listen to visibility change
- if ( visibilityEvent ) {
- document.addEventListener( visibilityEvent, this.onVisibilityChange, false );
- }
- // start ticking
- this.tick();
- };
- Player.prototype.tick = function() {
- // do not tick if not playing
- if ( this.state != 'playing' ) {
- return;
- }
- var time = this.parent.options.autoPlay;
- // default to 3 seconds
- time = typeof time == 'number' ? time : 3000;
- var _this = this;
- // HACK: reset ticks if stopped and started within interval
- this.clear();
- this.timeout = setTimeout( function() {
- _this.parent.next( true );
- _this.tick();
- }, time );
- };
- Player.prototype.stop = function() {
- this.state = 'stopped';
- this.clear();
- // remove visibility change event
- if ( visibilityEvent ) {
- document.removeEventListener( visibilityEvent, this.onVisibilityChange, false );
- }
- };
- Player.prototype.clear = function() {
- clearTimeout( this.timeout );
- };
- Player.prototype.pause = function() {
- if ( this.state == 'playing' ) {
- this.state = 'paused';
- this.clear();
- }
- };
- Player.prototype.unpause = function() {
- // re-start play if in unpaused state
- if ( this.state == 'paused' ) {
- this.play();
- }
- };
- // pause if page visibility is hidden, unpause if visible
- Player.prototype.visibilityChange = function() {
- var isHidden = document[ hiddenProperty ];
- this[ isHidden ? 'pause' : 'unpause' ]();
- };
- // -------------------------- Flickity -------------------------- //
- utils.extend( Flickity.defaults, {
- pauseAutoPlayOnHover: true
- });
- Flickity.createMethods.push('_createPlayer');
- Flickity.prototype._createPlayer = function() {
- this.player = new Player( this );
- this.on( 'activate', this.activatePlayer );
- this.on( 'uiChange', this.stopPlayer );
- this.on( 'pointerDown', this.stopPlayer );
- this.on( 'deactivate', this.deactivatePlayer );
- };
- Flickity.prototype.activatePlayer = function() {
- if ( !this.options.autoPlay ) {
- return;
- }
- this.player.play();
- eventie.bind( this.element, 'mouseenter', this );
- this.isMouseenterBound = true;
- };
- // Player API, don't hate the ... thanks I know where the door is
- Flickity.prototype.playPlayer = function() {
- this.player.play();
- };
- Flickity.prototype.stopPlayer = function() {
- this.player.stop();
- };
- Flickity.prototype.pausePlayer = function() {
- this.player.pause();
- };
- Flickity.prototype.unpausePlayer = function() {
- this.player.unpause();
- };
- Flickity.prototype.deactivatePlayer = function() {
- this.player.stop();
- if ( this.isMouseenterBound ) {
- eventie.unbind( this.element, 'mouseenter', this );
- delete this.isMouseenterBound;
- }
- };
- // ----- mouseenter/leave ----- //
- // pause auto-play on hover
- Flickity.prototype.onmouseenter = function() {
- if ( !this.options.pauseAutoPlayOnHover ) {
- return;
- }
- this.player.pause();
- eventie.bind( this.element, 'mouseleave', this );
- };
- // resume auto-play on hover off
- Flickity.prototype.onmouseleave = function() {
- this.player.unpause();
- eventie.unbind( this.element, 'mouseleave', this );
- };
- // ----- ----- //
- Flickity.Player = Player;
- return Flickity;
- }));
- },{"./flickity":13,"eventie":7,"fizzy-ui-utils":8,"wolfy87-eventemitter":24}],18:[function(require,module,exports){
- // -------------------------- prev/next button -------------------------- //
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'eventie/eventie',
- './flickity',
- 'tap-listener/tap-listener',
- 'fizzy-ui-utils/utils'
- ], function( eventie, Flickity, TapListener, utils ) {
- return factory( window, eventie, Flickity, TapListener, utils );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('eventie'),
- require('./flickity'),
- require('tap-listener'),
- require('fizzy-ui-utils')
- );
- } else {
- // browser global
- factory(
- window,
- window.eventie,
- window.Flickity,
- window.TapListener,
- window.fizzyUIUtils
- );
- }
- }( window, function factory( window, eventie, Flickity, TapListener, utils ) {
- 'use strict';
- // ----- inline SVG support ----- //
- var svgURI = 'http://www.w3.org/2000/svg';
- // only check on demand, not on script load
- var supportsInlineSVG = ( function() {
- var supports;
- function checkSupport() {
- if ( supports !== undefined ) {
- return supports;
- }
- var div = document.createElement('div');
- div.innerHTML = '<svg/>';
- supports = ( div.firstChild && div.firstChild.namespaceURI ) == svgURI;
- return supports;
- }
- return checkSupport;
- })();
- // -------------------------- PrevNextButton -------------------------- //
- function PrevNextButton( direction, parent ) {
- this.direction = direction;
- this.parent = parent;
- this._create();
- }
- PrevNextButton.prototype = new TapListener();
- PrevNextButton.prototype._create = function() {
- // properties
- this.isEnabled = true;
- this.isPrevious = this.direction == -1;
- var leftDirection = this.parent.options.rightToLeft ? 1 : -1;
- this.isLeft = this.direction == leftDirection;
- var element = this.element = document.createElement('button');
- element.className = 'flickity-prev-next-button';
- element.className += this.isPrevious ? ' previous' : ' next';
- // prevent button from submitting form http://stackoverflow.com/a/10836076/182183
- element.setAttribute( 'type', 'button' );
- // init as disabled
- this.disable();
- element.setAttribute( 'aria-label', this.isPrevious ? 'previous' : 'next' );
- Flickity.setUnselectable( element );
- // create arrow
- if ( supportsInlineSVG() ) {
- var svg = this.createSVG();
- element.appendChild( svg );
- } else {
- // SVG not supported, set button text
- this.setArrowText();
- element.className += ' no-svg';
- }
- // update on select
- var _this = this;
- this.onCellSelect = function() {
- _this.update();
- };
- this.parent.on( 'cellSelect', this.onCellSelect );
- // tap
- this.on( 'tap', this.onTap );
- // pointerDown
- this.on( 'pointerDown', function onPointerDown( button, event ) {
- _this.parent.childUIPointerDown( event );
- });
- };
- PrevNextButton.prototype.activate = function() {
- this.bindTap( this.element );
- // click events from keyboard
- eventie.bind( this.element, 'click', this );
- // add to DOM
- this.parent.element.appendChild( this.element );
- };
- PrevNextButton.prototype.deactivate = function() {
- // remove from DOM
- this.parent.element.removeChild( this.element );
- // do regular TapListener destroy
- TapListener.prototype.destroy.call( this );
- // click events from keyboard
- eventie.unbind( this.element, 'click', this );
- };
- PrevNextButton.prototype.createSVG = function() {
- var svg = document.createElementNS( svgURI, 'svg');
- svg.setAttribute( 'viewBox', '0 0 100 100' );
- var path = document.createElementNS( svgURI, 'path');
- var pathMovements = getArrowMovements( this.parent.options.arrowShape );
- path.setAttribute( 'd', pathMovements );
- path.setAttribute( 'class', 'arrow' );
- // rotate arrow
- if ( !this.isLeft ) {
- path.setAttribute( 'transform', 'translate(100, 100) rotate(180) ' );
- }
- svg.appendChild( path );
- return svg;
- };
- // get SVG path movmement
- function getArrowMovements( shape ) {
- // use shape as movement if string
- if ( typeof shape == 'string' ) {
- return shape;
- }
- // create movement string
- return 'M ' + shape.x0 + ',50' +
- ' L ' + shape.x1 + ',' + ( shape.y1 + 50 ) +
- ' L ' + shape.x2 + ',' + ( shape.y2 + 50 ) +
- ' L ' + shape.x3 + ',50 ' +
- ' L ' + shape.x2 + ',' + ( 50 - shape.y2 ) +
- ' L ' + shape.x1 + ',' + ( 50 - shape.y1 ) +
- ' Z';
- }
- PrevNextButton.prototype.setArrowText = function() {
- var parentOptions = this.parent.options;
- var arrowText = this.isLeft ? parentOptions.leftArrowText : parentOptions.rightArrowText;
- utils.setText( this.element, arrowText );
- };
- PrevNextButton.prototype.onTap = function() {
- if ( !this.isEnabled ) {
- return;
- }
- this.parent.uiChange();
- var method = this.isPrevious ? 'previous' : 'next';
- this.parent[ method ]();
- };
- PrevNextButton.prototype.handleEvent = utils.handleEvent;
- PrevNextButton.prototype.onclick = function() {
- // only allow clicks from keyboard
- var focused = document.activeElement;
- if ( focused && focused == this.element ) {
- this.onTap();
- }
- };
- // ----- ----- //
- PrevNextButton.prototype.enable = function() {
- if ( this.isEnabled ) {
- return;
- }
- this.element.disabled = false;
- this.isEnabled = true;
- };
- PrevNextButton.prototype.disable = function() {
- if ( !this.isEnabled ) {
- return;
- }
- this.element.disabled = true;
- this.isEnabled = false;
- };
- PrevNextButton.prototype.update = function() {
- // index of first or last cell, if previous or next
- var cells = this.parent.cells;
- // enable is wrapAround and at least 2 cells
- if ( this.parent.options.wrapAround && cells.length > 1 ) {
- this.enable();
- return;
- }
- var lastIndex = cells.length ? cells.length - 1 : 0;
- var boundIndex = this.isPrevious ? 0 : lastIndex;
- var method = this.parent.selectedIndex == boundIndex ? 'disable' : 'enable';
- this[ method ]();
- };
- PrevNextButton.prototype.destroy = function() {
- this.deactivate();
- };
- // -------------------------- Flickity prototype -------------------------- //
- utils.extend( Flickity.defaults, {
- prevNextButtons: true,
- leftArrowText: '‹',
- rightArrowText: '›',
- arrowShape: {
- x0: 10,
- x1: 60, y1: 50,
- x2: 70, y2: 40,
- x3: 30
- }
- });
- Flickity.createMethods.push('_createPrevNextButtons');
- Flickity.prototype._createPrevNextButtons = function() {
- if ( !this.options.prevNextButtons ) {
- return;
- }
- this.prevButton = new PrevNextButton( -1, this );
- this.nextButton = new PrevNextButton( 1, this );
- this.on( 'activate', this.activatePrevNextButtons );
- };
- Flickity.prototype.activatePrevNextButtons = function() {
- this.prevButton.activate();
- this.nextButton.activate();
- this.on( 'deactivate', this.deactivatePrevNextButtons );
- };
- Flickity.prototype.deactivatePrevNextButtons = function() {
- this.prevButton.deactivate();
- this.nextButton.deactivate();
- this.off( 'deactivate', this.deactivatePrevNextButtons );
- };
- // -------------------------- -------------------------- //
- Flickity.PrevNextButton = PrevNextButton;
- return Flickity;
- }));
- },{"./flickity":13,"eventie":7,"fizzy-ui-utils":8,"tap-listener":21}],19:[function(require,module,exports){
- /*!
- * getSize v1.2.2
- * measure size of elements
- * MIT license
- */
- /*jshint browser: true, strict: true, undef: true, unused: true */
- /*global define: false, exports: false, require: false, module: false, console: false */
- ( function( window, undefined ) {
- 'use strict';
- // -------------------------- helpers -------------------------- //
- // get a number from a string, not a percentage
- function getStyleSize( value ) {
- var num = parseFloat( value );
- // not a percent like '100%', and a number
- var isValid = value.indexOf('%') === -1 && !isNaN( num );
- return isValid && num;
- }
- function noop() {}
- var logError = typeof console === 'undefined' ? noop :
- function( message ) {
- console.error( message );
- };
- // -------------------------- measurements -------------------------- //
- var measurements = [
- 'paddingLeft',
- 'paddingRight',
- 'paddingTop',
- 'paddingBottom',
- 'marginLeft',
- 'marginRight',
- 'marginTop',
- 'marginBottom',
- 'borderLeftWidth',
- 'borderRightWidth',
- 'borderTopWidth',
- 'borderBottomWidth'
- ];
- function getZeroSize() {
- var size = {
- width: 0,
- height: 0,
- innerWidth: 0,
- innerHeight: 0,
- outerWidth: 0,
- outerHeight: 0
- };
- for ( var i=0, len = measurements.length; i < len; i++ ) {
- var measurement = measurements[i];
- size[ measurement ] = 0;
- }
- return size;
- }
- function defineGetSize( getStyleProperty ) {
- // -------------------------- setup -------------------------- //
- var isSetup = false;
- var getStyle, boxSizingProp, isBoxSizeOuter;
- /**
- * setup vars and functions
- * do it on initial getSize(), rather than on script load
- * For Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=548397
- */
- function setup() {
- // setup once
- if ( isSetup ) {
- return;
- }
- isSetup = true;
- var getComputedStyle = window.getComputedStyle;
- getStyle = ( function() {
- var getStyleFn = getComputedStyle ?
- function( elem ) {
- return getComputedStyle( elem, null );
- } :
- function( elem ) {
- return elem.currentStyle;
- };
- return function getStyle( elem ) {
- var style = getStyleFn( elem );
- if ( !style ) {
- logError( 'Style returned ' + style +
- '. Are you running this code in a hidden iframe on Firefox? ' +
- 'See http://bit.ly/getsizebug1' );
- }
- return style;
- };
- })();
- // -------------------------- box sizing -------------------------- //
- boxSizingProp = getStyleProperty('boxSizing');
- /**
- * WebKit measures the outer-width on style.width on border-box elems
- * IE & Firefox measures the inner-width
- */
- if ( boxSizingProp ) {
- var div = document.createElement('div');
- div.style.width = '200px';
- div.style.padding = '1px 2px 3px 4px';
- div.style.borderStyle = 'solid';
- div.style.borderWidth = '1px 2px 3px 4px';
- div.style[ boxSizingProp ] = 'border-box';
- var body = document.body || document.documentElement;
- body.appendChild( div );
- var style = getStyle( div );
- isBoxSizeOuter = getStyleSize( style.width ) === 200;
- body.removeChild( div );
- }
- }
- // -------------------------- getSize -------------------------- //
- function getSize( elem ) {
- setup();
- // use querySeletor if elem is string
- if ( typeof elem === 'string' ) {
- elem = document.querySelector( elem );
- }
- // do not proceed on non-objects
- if ( !elem || typeof elem !== 'object' || !elem.nodeType ) {
- return;
- }
- var style = getStyle( elem );
- // if hidden, everything is 0
- if ( style.display === 'none' ) {
- return getZeroSize();
- }
- var size = {};
- size.width = elem.offsetWidth;
- size.height = elem.offsetHeight;
- var isBorderBox = size.isBorderBox = !!( boxSizingProp &&
- style[ boxSizingProp ] && style[ boxSizingProp ] === 'border-box' );
- // get all measurements
- for ( var i=0, len = measurements.length; i < len; i++ ) {
- var measurement = measurements[i];
- var value = style[ measurement ];
- value = mungeNonPixel( elem, value );
- var num = parseFloat( value );
- // any 'auto', 'medium' value will be 0
- size[ measurement ] = !isNaN( num ) ? num : 0;
- }
- var paddingWidth = size.paddingLeft + size.paddingRight;
- var paddingHeight = size.paddingTop + size.paddingBottom;
- var marginWidth = size.marginLeft + size.marginRight;
- var marginHeight = size.marginTop + size.marginBottom;
- var borderWidth = size.borderLeftWidth + size.borderRightWidth;
- var borderHeight = size.borderTopWidth + size.borderBottomWidth;
- var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;
- // overwrite width and height if we can get it from style
- var styleWidth = getStyleSize( style.width );
- if ( styleWidth !== false ) {
- size.width = styleWidth +
- // add padding and border unless it's already including it
- ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
- }
- var styleHeight = getStyleSize( style.height );
- if ( styleHeight !== false ) {
- size.height = styleHeight +
- // add padding and border unless it's already including it
- ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
- }
- size.innerWidth = size.width - ( paddingWidth + borderWidth );
- size.innerHeight = size.height - ( paddingHeight + borderHeight );
- size.outerWidth = size.width + marginWidth;
- size.outerHeight = size.height + marginHeight;
- return size;
- }
- // IE8 returns percent values, not pixels
- // taken from jQuery's curCSS
- function mungeNonPixel( elem, value ) {
- // IE8 and has percent value
- if ( window.getComputedStyle || value.indexOf('%') === -1 ) {
- return value;
- }
- var style = elem.style;
- // Remember the original values
- var left = style.left;
- var rs = elem.runtimeStyle;
- var rsLeft = rs && rs.left;
- // Put in the new values to get a computed value out
- if ( rsLeft ) {
- rs.left = elem.currentStyle.left;
- }
- style.left = value;
- value = style.pixelLeft;
- // Revert the changed values
- style.left = left;
- if ( rsLeft ) {
- rs.left = rsLeft;
- }
- return value;
- }
- return getSize;
- }
- // transport
- if ( typeof define === 'function' && define.amd ) {
- // AMD for RequireJS
- define( [ 'get-style-property/get-style-property' ], defineGetSize );
- } else if ( typeof exports === 'object' ) {
- // CommonJS for Component
- module.exports = defineGetSize( require('desandro-get-style-property') );
- } else {
- // browser global
- window.getSize = defineGetSize( window.getStyleProperty );
- }
- })( window );
- },{"desandro-get-style-property":4}],20:[function(require,module,exports){
- /*
- * Backstretch
- * http://srobbin.com/jquery-plugins/backstretch/
- *
- * Copyright (c) 2013 Scott Robbin
- * Licensed under the MIT license.
- */
- ;(function ($, window, undefined) {
- 'use strict';
- /** @const */
- var YOUTUBE_REGEXP = /^.*(youtu\.be\/|youtube\.com\/v\/|youtube\.com\/embed\/|youtube\.com\/watch\?v=|youtube\.com\/watch\?.*\&v=)([^#\&\?]*).*/i;
- /* PLUGIN DEFINITION
- * ========================= */
- $.fn.backstretch = function (images, options) {
- var args = arguments;
- /*
- * Scroll the page one pixel to get the right window height on iOS
- * Pretty harmless for everyone else
- */
- if ($(window).scrollTop() === 0 ) {
- window.scrollTo(0, 0);
- }
- var returnValues;
- this.each(function (eachIndex) {
- var $this = $(this)
- , obj = $this.data('backstretch');
- // Do we already have an instance attached to this element?
- if (obj) {
- // Is this a method they're trying to execute?
- if (typeof args[0] === 'string' &&
- typeof obj[args[0]] === 'function') {
- // Call the method
- var returnValue = obj[args[0]].apply(obj, Array.prototype.slice.call(args, 1));
- if (returnValue === obj) { // If a method is chaining
- returnValue = undefined;
- }
- if (returnValue !== undefined) {
- returnValues = returnValues || [];
- returnValues[eachIndex] = returnValue;
- }
- return; // Nothing further to do
- }
- // Merge the old options with the new
- options = $.extend(obj.options, options);
- // Remove the old instance
- if ( obj.hasOwnProperty('destroy') ) {
- obj.destroy(true);
- }
- }
- // We need at least one image
- if (!images || (images && images.length === 0)) {
- var cssBackgroundImage = $this.css('background-image');
- if (cssBackgroundImage && cssBackgroundImage !== 'none') {
- images = [ { url: $this.css('backgroundImage').replace(/url\(|\)|"|'/g,"") } ];
- } else {
- $.error('No images were supplied for Backstretch, or element must have a CSS-defined background image.');
- }
- }
- obj = new Backstretch(this, images, options || {});
- $this.data('backstretch', obj);
- });
- return returnValues ? returnValues.length === 1 ? returnValues[0] : returnValues : this;
- };
- // If no element is supplied, we'll attach to body
- $.backstretch = function (images, options) {
- // Return the instance
- return $('body')
- .backstretch(images, options)
- .data('backstretch');
- };
- // Custom selector
- $.expr[':'].backstretch = function(elem) {
- return $(elem).data('backstretch') !== undefined;
- };
- /* DEFAULTS
- * ========================= */
- $.fn.backstretch.defaults = {
- duration: 5000 // Amount of time in between slides (if slideshow)
- , transition: 'fade' // Type of transition between slides
- , transitionDuration: 0 // Duration of transition between slides
- , animateFirst: true // Animate the transition of first image of slideshow in?
- , alignX: 0.5 // The x-alignment for the image, can be 'left'|'center'|'right' or any number between 0.0 and 1.0
- , alignY: 0.5 // The y-alignment for the image, can be 'top'|'center'|'bottom' or any number between 0.0 and 1.0
- , paused: false // Whether the images should slide after given duration
- , start: 0 // Index of the first image to show
- , preload: 2 // How many images preload at a time?
- , preloadSize: 1 // How many images can we preload in parallel?
- , resolutionRefreshRate: 2500 // How long to wait before switching resolution?
- , resolutionChangeRatioThreshold: 0.1 // How much a change should it be before switching resolution?
- };
- /* STYLES
- *
- * Baked-in styles that we'll apply to our elements.
- * In an effort to keep the plugin simple, these are not exposed as options.
- * That said, anyone can override these in their own stylesheet.
- * ========================= */
- var styles = {
- wrap: {
- left: 0
- , top: 0
- , overflow: 'hidden'
- , margin: 0
- , padding: 0
- , height: '100%'
- , width: '100%'
- , zIndex: -999999
- }
- , itemWrapper: {
- position: 'absolute'
- , display: 'none'
- , margin: 0
- , padding: 0
- , border: 'none'
- , width: '100%'
- , height: '100%'
- , zIndex: -999999
- }
- , item: {
- position: 'absolute'
- , margin: 0
- , padding: 0
- , border: 'none'
- , width: '100%'
- , height: '100%'
- , maxWidth: 'none'
- }
- };
- /* Given an array of different options for an image,
- * choose the optimal image for the container size.
- *
- * Given an image template (a string with {{ width }} and/or
- * {{height}} inside) and a container object, returns the
- * image url with the exact values for the size of that
- * container.
- *
- * Returns an array of urls optimized for the specified resolution.
- *
- */
- var optimalSizeImages = (function () {
- /* Sorts the array of image sizes based on width */
- var widthInsertSort = function (arr) {
- for (var i = 1; i < arr.length; i++) {
- var tmp = arr[i],
- j = i;
- while (arr[j - 1] && parseInt(arr[j - 1].width, 10) > parseInt(tmp.width, 10)) {
- arr[j] = arr[j - 1];
- --j;
- }
- arr[j] = tmp;
- }
- return arr;
- };
- /* Given an array of various sizes of the same image and a container width,
- * return the best image.
- */
- var selectBest = function (containerWidth, imageSizes) {
- var devicePixelRatio = window.devicePixelRatio || 1;
- var lastAllowedImage = 0;
- var testWidth;
- for (var j = 0, image; j < imageSizes.length; j++) {
- image = imageSizes[j];
- // In case a new image was pushed in, process it:
- if (typeof image === 'string') {
- image = imageSizes[j] = { url: image };
- }
- if (image.pixelRatio && image.pixelRatio !== 'auto' && parseFloat(image.pixelRatio) !== devicePixelRatio) {
- // We disallowed choosing this image for current device pixel ratio,
- // So skip this one.
- continue;
- }
- // Mark this one as the last one we investigated
- // which does not violate device pixel ratio rules.
- // We may choose this one later if there's no match.
- lastAllowedImage = j;
- // For most images, we match the specified width against element width,
- // And enforcing a limit depending on the "pixelRatio" property if specified.
- // But if a pixelRatio="auto", then we consider the width as the physical width of the image,
- // And match it while considering the device's pixel ratio.
- testWidth = containerWidth;
- if (image.pixelRatio === 'auto') {
- containerWidth *= devicePixelRatio;
- }
- // Stop when the width of the image is larger or equal to the container width
- if (image.width >= testWidth) {
- break;
- }
- }
- // Use the image located at where we stopped
- return imageSizes[Math.min(j, lastAllowedImage)];
- };
- var replaceTagsInUrl = function (url, templateReplacer) {
- if (typeof url === 'string') {
- url = url.replace(/{{(width|height)}}/g, templateReplacer);
- } else if (url instanceof Array) {
- for (var i = 0; i < url.length; i++) {
- if (url[i].src) {
- url[i].src = replaceTagsInUrl(url[i].src, templateReplacer);
- } else {
- url[i] = replaceTagsInUrl(url[i], templateReplacer);
- }
- }
- }
- return url;
- };
- return function ($container, images) {
- var containerWidth = $container.width(),
- containerHeight = $container.height();
- var chosenImages = [];
- var templateReplacer = function (match, key) {
- if (key === 'width') {
- return containerWidth;
- }
- if (key === 'height') {
- return containerHeight;
- }
- return match;
- };
- for (var i = 0; i < images.length; i++) {
- if ($.isArray(images[i])) {
- images[i] = widthInsertSort(images[i]);
- var chosen = selectBest(containerWidth, images[i]);
- chosenImages.push(chosen);
- } else {
- // In case a new image was pushed in, process it:
- if (typeof images[i] === 'string') {
- images[i] = { url: images[i] };
- }
- var item = $.extend({}, images[i]);
- item.url = replaceTagsInUrl(item.url, templateReplacer);
- chosenImages.push(item);
- }
- }
- return chosenImages;
- };
- })();
- var isVideoSource = function (source) {
- return YOUTUBE_REGEXP.test(source.url) || source.isVideo;
- };
- /* Preload images */
- var preload = (function (sources, startAt, count, batchSize, callback) {
- // Plugin cache
- var cache = [];
- // Wrapper for cache
- var caching = function(image){
- for (var i = 0; i < cache.length; i++) {
- if (cache[i].src === image.src) {
- return cache[i];
- }
- }
- cache.push(image);
- return image;
- };
- // Execute callback
- var exec = function(sources, callback, last){
- if (typeof callback === 'function') {
- callback.call(sources, last);
- }
- };
- // Closure to hide cache
- return function preload (sources, startAt, count, batchSize, callback){
- // Check input data
- if (typeof sources === 'undefined') {
- return;
- }
- if (!$.isArray(sources)) {
- sources = [sources];
- }
- if (arguments.length < 5 && typeof arguments[arguments.length - 1] === 'function') {
- callback = arguments[arguments.length - 1];
- }
- startAt = (typeof startAt === 'function' || !startAt) ? 0 : startAt;
- count = (typeof count === 'function' || !count || count < 0) ? sources.length : Math.min(count, sources.length);
- batchSize = (typeof batchSize === 'function' || !batchSize) ? 1 : batchSize;
- if (startAt >= sources.length) {
- startAt = 0;
- count = 0;
- }
- if (batchSize < 0) {
- batchSize = count;
- }
- batchSize = Math.min(batchSize, count);
- var next = sources.slice(startAt + batchSize, count - batchSize);
- sources = sources.slice(startAt, batchSize);
- count = sources.length;
- // If sources array is empty
- if (!count) {
- exec(sources, callback, true);
- return;
- }
- // Image loading callback
- var countLoaded = 0;
- var loaded = function() {
- countLoaded++;
- if (countLoaded !== count) {
- return;
- }
- exec(sources, callback, !next);
- preload(next, 0, 0, batchSize, callback);
- };
- // Loop sources to preload
- var image;
- for (var i = 0; i < sources.length; i++) {
- if (isVideoSource(sources[i])) {
- // Do not preload videos. There are issues with that.
- // First - we need to keep an instance of the preloaded and use that exactly, not a copy.
- // Second - there are memory issues.
- // If there will be a requirement from users - I'll try to implement this.
- continue;
- } else {
- image = new Image();
- image.src = sources[i].url;
- image = caching(image);
- if (image.complete) {
- loaded();
- } else {
- $(image).on('load error', loaded);
- }
- }
- }
- };
- })();
- /* Process images array */
- var processImagesArray = function (images) {
- var processed = [];
- for (var i = 0; i < images.length; i++) {
- if (typeof images[i] === 'string') {
- processed.push({ url: images[i] });
- }
- else if ($.isArray(images[i])) {
- processed.push(processImagesArray(images[i]));
- }
- else {
- processed.push(processOptions(images[i]));
- }
- }
- return processed;
- };
- /* Process options */
- var processOptions = function (options, required) {
- // Convert old options
- // centeredX/centeredY are deprecated
- if (options.centeredX || options.centeredY) {
- if (window.console && window.console.log) {
- window.console.log('jquery.backstretch: `centeredX`/`centeredY` is deprecated, please use `alignX`/`alignY`');
- }
- if (options.centeredX) {
- options.alignX = 0.5;
- }
- if (options.centeredY) {
- options.alignY = 0.5;
- }
- }
- // Deprecated spec
- if (options.speed !== undefined) {
- if (window.console && window.console.log) {
- window.console.log('jquery.backstretch: `speed` is deprecated, please use `transitionDuration`');
- }
- options.transitionDuration = options.speed;
- options.transition = 'fade';
- }
- // Typo
- if (options.resolutionChangeRatioTreshold !== undefined) {
- window.console.log('jquery.backstretch: `treshold` is a typo!');
- options.resolutionChangeRatioThreshold = options.resolutionChangeRatioTreshold;
- }
- // Current spec that needs processing
- if (options.fadeFirst !== undefined) {
- options.animateFirst = options.fadeFirst;
- }
- if (options.fade !== undefined) {
- options.transitionDuration = options.fade;
- options.transition = 'fade';
- }
- return processAlignOptions(options);
- };
- /* Process align options */
- var processAlignOptions = function (options, required) {
- if (options.alignX === 'left') {
- options.alignX = 0.0;
- }
- else if (options.alignX === 'center') {
- options.alignX = 0.5;
- }
- else if (options.alignX === 'right') {
- options.alignX = 1.0;
- }
- else {
- if (options.alignX !== undefined || required) {
- options.alignX = parseFloat(options.alignX);
- if (isNaN(options.alignX)) {
- options.alignX = 0.5;
- }
- }
- }
- if (options.alignY === 'top') {
- options.alignY = 0.0;
- }
- else if (options.alignY === 'center') {
- options.alignY = 0.5;
- }
- else if (options.alignY === 'bottom') {
- options.alignY = 1.0;
- }
- else {
- if (options.alignX !== undefined || required) {
- options.alignY = parseFloat(options.alignY);
- if (isNaN(options.alignY)) {
- options.alignY = 0.5;
- }
- }
- }
- return options;
- };
- /* CLASS DEFINITION
- * ========================= */
- var Backstretch = function (container, images, options) {
- this.options = $.extend({}, $.fn.backstretch.defaults, options || {});
- this.firstShow = true;
- // Process options
- processOptions(this.options, true);
- /* In its simplest form, we allow Backstretch to be called on an image path.
- * e.g. $.backstretch('/path/to/image.jpg')
- * So, we need to turn this back into an array.
- */
- this.images = processImagesArray($.isArray(images) ? images : [images]);
- /**
- * Paused-Option
- */
- if (this.options.paused) {
- this.paused = true;
- }
- /**
- * Start-Option (Index)
- */
- if (this.options.start >= this.images.length)
- {
- this.options.start = this.images.length - 1;
- }
- if (this.options.start < 0)
- {
- this.options.start = 0;
- }
- // Convenience reference to know if the container is body.
- this.isBody = container === document.body;
- /* We're keeping track of a few different elements
- *
- * Container: the element that Backstretch was called on.
- * Wrap: a DIV that we place the image into, so we can hide the overflow.
- * Root: Convenience reference to help calculate the correct height.
- */
- var $window = $(window);
- this.$container = $(container);
- this.$root = this.isBody ? supportsFixedPosition ? $window : $(document) : this.$container;
- this.originalImages = this.images;
- this.images = optimalSizeImages(
- this.options.alwaysTestWindowResolution ? $window : this.$root,
- this.originalImages);
- /**
- * Pre-Loading.
- * This is the first image, so we will preload a minimum of 1 images.
- */
- preload(this.images, this.options.start || 0, this.options.preload || 1);
- // Don't create a new wrap if one already exists (from a previous instance of Backstretch)
- var $existing = this.$container.children(".backstretch").first();
- this.$wrap = $existing.length ? $existing :
- $('<div class="backstretch"></div>')
- .css(this.options.bypassCss ? {} : styles.wrap)
- .appendTo(this.$container);
- if (!this.options.bypassCss) {
- // Non-body elements need some style adjustments
- if (!this.isBody) {
- // If the container is statically positioned, we need to make it relative,
- // and if no zIndex is defined, we should set it to zero.
- var position = this.$container.css('position')
- , zIndex = this.$container.css('zIndex');
- this.$container.css({
- position: position === 'static' ? 'relative' : position
- , zIndex: zIndex === 'auto' ? 0 : zIndex
- });
- // Needs a higher z-index
- this.$wrap.css({zIndex: -999998});
- }
- // Fixed or absolute positioning?
- this.$wrap.css({
- position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute'
- });
- }
- // Set the first image
- this.index = this.options.start;
- this.show(this.index);
- // Listen for resize
- $window.on('resize.backstretch', $.proxy(this.resize, this))
- .on('orientationchange.backstretch', $.proxy(function () {
- // Need to do this in order to get the right window height
- if (this.isBody && window.pageYOffset === 0) {
- window.scrollTo(0, 1);
- this.resize();
- }
- }, this));
- };
- var performTransition = function (options) {
- var transition = options.transition || 'fade';
- // Look for multiple options
- if (typeof transition === 'string' && transition.indexOf('|') > -1) {
- transition = transition.split('|');
- }
- if (transition instanceof Array) {
- transition = transition[Math.round(Math.random() * (transition.length - 1))];
- }
- var $new = options['new'];
- var $old = options['old'] ? options['old'] : $([]);
- switch (transition.toString().toLowerCase()) {
- default:
- case 'fade':
- $new.fadeIn({
- duration: options.duration,
- complete: options.complete,
- easing: options.easing || undefined
- });
- break;
- case 'fadeinout':
- case 'fade_in_out':
- var fadeInNew = function () {
- $new.fadeIn({
- duration: options.duration / 2,
- complete: options.complete,
- easing: options.easing || undefined
- });
- };
- if ($old.length) {
- $old.fadeOut({
- duration: options.duration / 2,
- complete: fadeInNew,
- easing: options.easing || undefined
- });
- } else {
- fadeInNew();
- }
- break;
- case 'pushleft':
- case 'push_left':
- case 'pushright':
- case 'push_right':
- case 'pushup':
- case 'push_up':
- case 'pushdown':
- case 'push_down':
- case 'coverleft':
- case 'cover_left':
- case 'coverright':
- case 'cover_right':
- case 'coverup':
- case 'cover_up':
- case 'coverdown':
- case 'cover_down':
- var transitionParts = transition.match(/^(cover|push)_?(.*)$/);
- var animProp = transitionParts[2] === 'left' ? 'right' :
- transitionParts[2] === 'right' ? 'left' :
- transitionParts[2] === 'down' ? 'top' :
- transitionParts[2] === 'up' ? 'bottom' :
- 'right';
- var newCssStart = {
- 'display': ''
- }, newCssAnim = {};
- newCssStart[animProp] = '-100%';
- newCssAnim[animProp] = 0;
- $new
- .css(newCssStart)
- .animate(newCssAnim, {
- duration: options.duration,
- complete: function () {
- $new.css(animProp, '');
- options.complete.apply(this, arguments);
- },
- easing: options.easing || undefined
- });
- if (transitionParts[1] === 'push' && $old.length) {
- var oldCssAnim = {};
- oldCssAnim[animProp] = '100%';
- $old
- .animate(oldCssAnim, {
- duration: options.duration,
- complete: function () {
- $old.css('display', 'none');
- },
- easing: options.easing || undefined
- });
- }
- break;
- }
- };
- /* PUBLIC METHODS
- * ========================= */
- Backstretch.prototype = {
- resize: function () {
- try {
- // Check for a better suited image after the resize
- var $resTest = this.options.alwaysTestWindowResolution ? $(window) : this.$root;
- var newContainerWidth = $resTest.width();
- var newContainerHeight = $resTest.height();
- var changeRatioW = newContainerWidth / (this._lastResizeContainerWidth || 0);
- var changeRatioH = newContainerHeight / (this._lastResizeContainerHeight || 0);
- var resolutionChangeRatioThreshold = this.options.resolutionChangeRatioThreshold || 0.0;
- // check for big changes in container size
- if ((newContainerWidth !== this._lastResizeContainerWidth ||
- newContainerHeight !== this._lastResizeContainerHeight) &&
- ((Math.abs(changeRatioW - 1) >= resolutionChangeRatioThreshold || isNaN(changeRatioW)) ||
- (Math.abs(changeRatioH - 1) >= resolutionChangeRatioThreshold || isNaN(changeRatioH)))) {
- this._lastResizeContainerWidth = newContainerWidth;
- this._lastResizeContainerHeight = newContainerHeight;
- // Big change: rebuild the entire images array
- this.images = optimalSizeImages($resTest, this.originalImages);
- // Preload them (they will be automatically inserted on the next cycle)
- if (this.options.preload) {
- preload(this.images, (this.index + 1) % this.images.length, this.options.preload);
- }
- // In case there is no cycle and the new source is different than the current
- if (this.images.length === 1 &&
- this._currentImage.url !== this.images[0].url) {
- // Wait a little an update the image being showed
- var that = this;
- clearTimeout(that._selectAnotherResolutionTimeout);
- that._selectAnotherResolutionTimeout = setTimeout(function () {
- that.show(0);
- }, this.options.resolutionRefreshRate);
- }
- }
- var bgCSS = {left: 0, top: 0, right: 'auto', bottom: 'auto'}
- , rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth()
- , rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight()
- , bgWidth = rootWidth
- , bgHeight = bgWidth / this.$itemWrapper.data('ratio')
- , evt = $.Event('backstretch.resize', {
- relatedTarget: this.$container[0]
- })
- , bgOffset
- , alignX = this._currentImage.alignX === undefined ? this.options.alignX : this._currentImage.alignX
- , alignY = this._currentImage.alignY === undefined ? this.options.alignY : this._currentImage.alignY;
- // Make adjustments based on image ratio
- if (bgHeight >= rootHeight) {
- bgCSS.top = -(bgHeight - rootHeight) * alignY;
- } else {
- bgHeight = rootHeight;
- bgWidth = bgHeight * this.$itemWrapper.data('ratio');
- bgOffset = (bgWidth - rootWidth) / 2;
- bgCSS.left = -(bgWidth - rootWidth) * alignX;
- }
- if (!this.options.bypassCss) {
- this.$wrap
- .css({width: rootWidth, height: rootHeight})
- .find('>.backstretch-item').not('.deleteable')
- .each(function () {
- var $wrapper = $(this);
- $wrapper.find('img,video,iframe')
- .css({width: bgWidth, height: bgHeight})
- .css(bgCSS);
- });
- }
- this.$container.trigger(evt, this);
- } catch(err) {
- // IE7 seems to trigger resize before the image is loaded.
- // This try/catch block is a hack to let it fail gracefully.
- }
- return this;
- }
- // Show the slide at a certain position
- , show: function (newIndex, overrideOptions) {
- // Validate index
- if (Math.abs(newIndex) > this.images.length - 1) {
- return;
- }
- // Vars
- var that = this
- , $oldItemWrapper = that.$wrap.find('>.backstretch-item').addClass('deleteable')
- , oldVideoWrapper = that.videoWrapper
- , evtOptions = { relatedTarget: that.$container[0] };
- // Trigger the "before" event
- that.$container.trigger($.Event('backstretch.before', evtOptions), [that, newIndex]);
- // Set the new frame index
- this.index = newIndex;
- var selectedImage = that.images[newIndex];
- // Pause the slideshow
- clearTimeout(that._cycleTimeout);
- // New image
- delete that.videoWrapper; // Current item may not be a video
- var isVideo = isVideoSource(selectedImage);
- if (isVideo) {
- that.videoWrapper = new VideoWrapper(selectedImage);
- that.$item = that.videoWrapper.$video.css('pointer-events', 'none');
- } else {
- that.$item = $('<img />');
- }
- that.$itemWrapper = $('<div class="backstretch-item">')
- .append(that.$item);
- if (this.options.bypassCss) {
- that.$itemWrapper.css({
- 'display': 'none'
- });
- } else {
- that.$itemWrapper.css(styles.itemWrapper);
- that.$item.css(styles.item);
- }
- that.$item.bind(isVideo ? 'canplay' : 'load', function (e) {
- var $this = $(this)
- , $wrapper = $this.parent()
- , options = $wrapper.data('options');
- if (overrideOptions) {
- options = $.extend({}, options, overrideOptions);
- }
- var imgWidth = this.naturalWidth || this.videoWidth || this.width
- , imgHeight = this.naturalHeight || this.videoHeight || this.height;
- // Save the ratio
- $wrapper.data('ratio', imgWidth / imgHeight);
- var getOption = function (opt) {
- return options[opt] !== undefined ?
- options[opt] :
- that.options[opt];
- };
- var transition = getOption('transition');
- var transitionEasing = getOption('transitionEasing');
- var transitionDuration = getOption('transitionDuration');
- // Show the image, then delete the old one
- var bringInNextImage = function () {
- if (oldVideoWrapper) {
- oldVideoWrapper.stop();
- oldVideoWrapper.destroy();
- }
- $oldItemWrapper.remove();
- // Resume the slideshow
- if (!that.paused && that.images.length > 1) {
- that.cycle();
- }
- // Now we can clear the background on the element, to spare memory
- if (!that.options.bypassCss && !that.isBody) {
- that.$container.css('background', 'none');
- }
- // Trigger the "after" and "show" events
- // "show" is being deprecated
- $(['after', 'show']).each(function () {
- that.$container.trigger($.Event('backstretch.' + this, evtOptions), [that, newIndex]);
- });
- if (isVideo) {
- that.videoWrapper.play();
- }
- };
- if ((that.firstShow && !that.options.animateFirst) || !transitionDuration || !transition) {
- // Avoid transition on first show or if there's no transitionDuration value
- $wrapper.show();
- bringInNextImage();
- } else {
- performTransition({
- 'new': $wrapper,
- old: $oldItemWrapper,
- transition: transition,
- duration: transitionDuration,
- easing: transitionEasing,
- complete: bringInNextImage
- });
- }
- that.firstShow = false;
- // Resize
- that.resize();
- });
- that.$itemWrapper.appendTo(that.$wrap);
- that.$item.attr('alt', selectedImage.alt || '');
- that.$itemWrapper.data('options', selectedImage);
- if (!isVideo) {
- that.$item.attr('src', selectedImage.url);
- }
- that._currentImage = selectedImage;
- return that;
- }
- , current: function () {
- return this.index;
- }
- , next: function () {
- var args = Array.prototype.slice.call(arguments, 0);
- args.unshift(this.index < this.images.length - 1 ? this.index + 1 : 0);
- return this.show.apply(this, args);
- }
- , prev: function () {
- var args = Array.prototype.slice.call(arguments, 0);
- args.unshift(this.index === 0 ? this.images.length - 1 : this.index - 1);
- return this.show.apply(this, args);
- }
- , pause: function () {
- // Pause the slideshow
- this.paused = true;
- if (this.videoWrapper) {
- this.videoWrapper.pause();
- }
- return this;
- }
- , resume: function () {
- // Resume the slideshow
- this.paused = false;
- if (this.videoWrapper) {
- this.videoWrapper.play();
- }
- this.cycle();
- return this;
- }
- , cycle: function () {
- // Start/resume the slideshow
- if(this.images.length > 1) {
- // Clear the timeout, just in case
- clearTimeout(this._cycleTimeout);
- var duration = (this._currentImage && this._currentImage.duration) || this.options.duration;
- var isVideo = isVideoSource(this._currentImage);
- var callNext = function () {
- this.$item.off('.cycle');
- // Check for paused slideshow
- if (!this.paused) {
- this.next();
- }
- };
- // Special video handling
- if (isVideo) {
- // Leave video at last frame
- if (!this._currentImage.loop) {
- var lastFrameTimeout = 0;
- this.$item
- .on('playing.cycle', function () {
- var player = $(this).data('player');
- clearTimeout(lastFrameTimeout);
- lastFrameTimeout = setTimeout(function () {
- player.pause();
- player.$video.trigger('ended');
- }, (player.getDuration() - player.getCurrentTime()) * 1000);
- })
- .on('ended.cycle', function () {
- clearTimeout(lastFrameTimeout);
- });
- }
- // On error go to next
- this.$item.on('error.cycle initerror.cycle', $.proxy(callNext, this));
- }
- if (isVideo && !this._currentImage.duration) {
- // It's a video - playing until end
- this.$item.on('ended.cycle', $.proxy(callNext, this));
- } else {
- // Cycling according to specified duration
- this._cycleTimeout = setTimeout($.proxy(callNext, this), duration);
- }
- }
- return this;
- }
- , destroy: function (preserveBackground) {
- // Stop the resize events
- $(window).off('resize.backstretch orientationchange.backstretch');
- // Stop any videos
- if (this.videoWrapper) {
- this.videoWrapper.destroy();
- }
- // Clear the timeout
- clearTimeout(this._cycleTimeout);
- // Remove Backstretch
- if(!preserveBackground) {
- this.$wrap.remove();
- }
- this.$container.removeData('backstretch');
- }
- };
- /**
- * Video Abstraction Layer
- *
- * Static methods:
- * > VideoWrapper.loadYoutubeAPI() -> Call in order to load the Youtube API.
- * An 'youtube_api_load' event will be triggered on $(window) when the API is loaded.
- *
- * Generic:
- * > player.type -> type of the video
- * > player.video / player.$video -> contains the element holding the video
- * > player.play() -> plays the video
- * > player.pause() -> pauses the video
- * > player.setCurrentTime(position) -> seeks to a position by seconds
- *
- * Youtube:
- * > player.ytId will contain the youtube ID if the source is a youtube url
- * > player.ytReady is a flag telling whether the youtube source is ready for playback
- * */
- var VideoWrapper = function () { this.init.apply(this, arguments); };
- /**
- * @param {Object} options
- * @param {String|Array<String>|Array<{{src: String, type: String?}}>} options.url
- * @param {Boolean} options.loop=false
- * @param {Boolean?} options.mute=true
- * @param {String?} options.poster
- * loop, mute, poster
- */
- VideoWrapper.prototype.init = function (options) {
- var that = this;
- var $video;
- var setVideoElement = function () {
- that.$video = $video;
- that.video = $video[0];
- };
- // Determine video type
- var videoType = 'video';
- if (!(options.url instanceof Array) &&
- YOUTUBE_REGEXP.test(options.url)) {
- videoType = 'youtube';
- }
- that.type = videoType;
- if (videoType === 'youtube') {
- // Try to load the API in the meantime
- VideoWrapper.loadYoutubeAPI();
- that.ytId = options.url.match(YOUTUBE_REGEXP)[2];
- var src = 'https://www.youtube.com/embed/' + that.ytId +
- '?rel=0&autoplay=0&showinfo=0&controls=0&modestbranding=1' +
- '&cc_load_policy=0&disablekb=1&iv_load_policy=3&loop=0' +
- '&enablejsapi=1&origin=' + encodeURIComponent(window.location.origin);
- that.__ytStartMuted = !!options.mute || options.mute === undefined;
- $video = $('<iframe />')
- .attr({ 'src_to_load': src })
- .css({ 'border': 0, 'margin': 0, 'padding': 0 })
- .data('player', that);
- if (options.loop) {
- $video.on('ended.loop', function () {
- if (!that.__manuallyStopped) {
- that.play();
- }
- });
- }
- that.ytReady = false;
- setVideoElement();
- if (window['YT']) {
- that._initYoutube();
- $video.trigger('initsuccess');
- } else {
- $(window).one('youtube_api_load', function () {
- that._initYoutube();
- $video.trigger('initsuccess');
- });
- }
- }
- else {
- // Traditional <video> tag with multiple sources
- $video = $('<video>')
- .prop('autoplay', false)
- .prop('controls', false)
- .prop('loop', !!options.loop)
- .prop('muted', !!options.mute || options.mute === undefined)
- // Let the first frames be available before playback, as we do transitions
- .prop('preload', 'auto')
- .prop('poster', options.poster || '');
- var sources = (options.url instanceof Array) ? options.url : [options.url];
- for (var i = 0; i < sources.length; i++) {
- var sourceItem = sources[i];
- if (typeof(sourceItem) === 'string') {
- sourceItem = { src: sourceItem };
- }
- $('<source>')
- .attr('src', sourceItem.src)
- // Make sure to not specify type if unknown -
- // so the browser will try to autodetect.
- .attr('type', sourceItem.type || null)
- .appendTo($video);
- }
- if (!$video[0].canPlayType || !sources.length) {
- $video.trigger('initerror');
- } else {
- $video.trigger('initsuccess');
- }
- setVideoElement();
- }
- };
- VideoWrapper.prototype._initYoutube = function () {
- var that = this;
- var YT = window['YT'];
- that.$video
- .attr('src', that.$video.attr('src_to_load'))
- .removeAttr('src_to_load');
- // It won't init if it's not in the DOM, so we emulate that
- var hasParent = !!that.$video[0].parentNode;
- if (!hasParent) {
- var $tmpParent = $('<div>').css('display', 'none !important').appendTo(document.body);
- that.$video.appendTo($tmpParent);
- }
- var player = new YT.Player(that.video, {
- events: {
- 'onReady': function () {
- if (that.__ytStartMuted) {
- player.mute();
- }
- if (!hasParent) {
- // Restore parent to old state - without interrupting any changes
- if (that.$video[0].parentNode === $tmpParent[0]) {
- that.$video.detach();
- }
- $tmpParent.remove();
- }
- that.ytReady = true;
- that._updateYoutubeSize();
- that.$video.trigger('canplay');
- },
- 'onStateChange': function (event) {
- switch (event.data) {
- case YT.PlayerState.PLAYING:
- that.$video.trigger('playing');
- break;
- case YT.PlayerState.ENDED:
- that.$video.trigger('ended');
- break;
- case YT.PlayerState.PAUSED:
- that.$video.trigger('pause');
- break;
- case YT.PlayerState.BUFFERING:
- that.$video.trigger('waiting');
- break;
- case YT.PlayerState.CUED:
- that.$video.trigger('canplay');
- break;
- }
- },
- 'onPlaybackQualityChange': function () {
- that._updateYoutubeSize();
- that.$video.trigger('resize');
- },
- 'onError': function (err) {
- that.hasError = true;
- that.$video.trigger({ 'type': 'error', 'error': err });
- }
- }
- });
- that.ytPlayer = player;
- return that;
- };
- VideoWrapper.prototype._updateYoutubeSize = function () {
- var that = this;
- switch (that.ytPlayer.getPlaybackQuality() || 'medium') {
- case 'small':
- that.video.videoWidth = 426;
- that.video.videoHeight = 240;
- break;
- case 'medium':
- that.video.videoWidth = 640;
- that.video.videoHeight = 360;
- break;
- default:
- case 'large':
- that.video.videoWidth = 854;
- that.video.videoHeight = 480;
- break;
- case 'hd720':
- that.video.videoWidth = 1280;
- that.video.videoHeight = 720;
- break;
- case 'hd1080':
- that.video.videoWidth = 1920;
- that.video.videoHeight = 1080;
- break;
- case 'highres':
- that.video.videoWidth = 2560;
- that.video.videoHeight = 1440;
- break;
- }
- return that;
- };
- VideoWrapper.prototype.play = function () {
- var that = this;
- that.__manuallyStopped = false;
- if (that.type === 'youtube') {
- if (that.ytReady) {
- that.$video.trigger('play');
- that.ytPlayer.playVideo();
- }
- } else {
- that.video.play();
- }
- return that;
- };
- VideoWrapper.prototype.pause = function () {
- var that = this;
- that.__manuallyStopped = false;
- if (that.type === 'youtube') {
- if (that.ytReady) {
- that.ytPlayer.pauseVideo();
- }
- } else {
- that.video.pause();
- }
- return that;
- };
- VideoWrapper.prototype.stop = function () {
- var that = this;
- that.__manuallyStopped = true;
- if (that.type === 'youtube') {
- if (that.ytReady) {
- that.ytPlayer.pauseVideo();
- that.ytPlayer.seekTo(0);
- }
- } else {
- that.video.pause();
- that.video.currentTime = 0;
- }
- return that;
- };
- VideoWrapper.prototype.destroy = function () {
- var that = this;
- if (that.ytPlayer) {
- that.ytPlayer.destroy();
- }
- that.$video.remove();
- return that;
- };
- VideoWrapper.prototype.getCurrentTime = function (seconds) {
- var that = this;
- if (that.type === 'youtube') {
- if (that.ytReady) {
- return that.ytPlayer.getCurrentTime();
- }
- } else {
- return that.video.currentTime;
- }
- return 0;
- };
- VideoWrapper.prototype.setCurrentTime = function (seconds) {
- var that = this;
- if (that.type === 'youtube') {
- if (that.ytReady) {
- that.ytPlayer.seekTo(seconds, true);
- }
- } else {
- that.video.currentTime = seconds;
- }
- return that;
- };
- VideoWrapper.prototype.getDuration = function () {
- var that = this;
- if (that.type === 'youtube') {
- if (that.ytReady) {
- return that.ytPlayer.getDuration();
- }
- } else {
- return that.video.duration;
- }
- return 0;
- };
- /**
- * This will load the youtube API (if not loaded yet)
- * Use $(window).one('youtube_api_load', ...) to listen for API loaded event
- */
- VideoWrapper.loadYoutubeAPI = function () {
- if (window['YT']) {
- return;
- }
- if (!$('script[src*=www\\.youtube\\.com\\/iframe_api]').length) {
- $('<script type="text/javascript" src="https://www.youtube.com/iframe_api">').appendTo('body');
- }
- var ytAPILoadInt = setInterval(function () {
- if (window['YT'] && window['YT'].loaded) {
- $(window).trigger('youtube_api_load');
- clearTimeout(ytAPILoadInt);
- }
- }, 50);
- };
- /* SUPPORTS FIXED POSITION?
- *
- * Based on code from jQuery Mobile 1.1.0
- * http://jquerymobile.com/
- *
- * In a nutshell, we need to figure out if fixed positioning is supported.
- * Unfortunately, this is very difficult to do on iOS, and usually involves
- * injecting content, scrolling the page, etc.. It's ugly.
- * jQuery Mobile uses this workaround. It's not ideal, but works.
- *
- * Modified to detect IE6
- * ========================= */
- var supportsFixedPosition = (function () {
- var ua = navigator.userAgent
- , platform = navigator.platform
- // Rendering engine is Webkit, and capture major version
- , wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ )
- , wkversion = !!wkmatch && wkmatch[ 1 ]
- , ffmatch = ua.match( /Fennec\/([0-9]+)/ )
- , ffversion = !!ffmatch && ffmatch[ 1 ]
- , operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ )
- , omversion = !!operammobilematch && operammobilematch[ 1 ]
- , iematch = ua.match( /MSIE ([0-9]+)/ )
- , ieversion = !!iematch && iematch[ 1 ];
- return !(
- // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5)
- ((platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534) ||
- // Opera Mini
- (window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]") ||
- (operammobilematch && omversion < 7458) ||
- //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2)
- (ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533) ||
- // Firefox Mobile before 6.0 -
- (ffversion && ffversion < 6) ||
- // WebOS less than 3
- ("palmGetResource" in window && wkversion && wkversion < 534) ||
- // MeeGo
- (ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1) ||
- // IE6
- (ieversion && ieversion <= 6)
- );
- }());
- }(jQuery, window));
- },{}],21:[function(require,module,exports){
- /*!
- * Tap listener v1.1.2
- * listens to taps
- * MIT license
- */
- /*jshint browser: true, unused: true, undef: true, strict: true */
- ( function( window, factory ) {
- // universal module definition
- /*jshint strict: false*/ /*globals define, module, require */
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'unipointer/unipointer'
- ], function( Unipointer ) {
- return factory( window, Unipointer );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('unipointer')
- );
- } else {
- // browser global
- window.TapListener = factory(
- window,
- window.Unipointer
- );
- }
- }( window, function factory( window, Unipointer ) {
- 'use strict';
- // -------------------------- TapListener -------------------------- //
- function TapListener( elem ) {
- this.bindTap( elem );
- }
- // inherit Unipointer & EventEmitter
- TapListener.prototype = new Unipointer();
- /**
- * bind tap event to element
- * @param {Element} elem
- */
- TapListener.prototype.bindTap = function( elem ) {
- if ( !elem ) {
- return;
- }
- this.unbindTap();
- this.tapElement = elem;
- this._bindStartEvent( elem, true );
- };
- TapListener.prototype.unbindTap = function() {
- if ( !this.tapElement ) {
- return;
- }
- this._bindStartEvent( this.tapElement, true );
- delete this.tapElement;
- };
- var isPageOffset = window.pageYOffset !== undefined;
- /**
- * pointer up
- * @param {Event} event
- * @param {Event or Touch} pointer
- */
- TapListener.prototype.pointerUp = function( event, pointer ) {
- // ignore emulated mouse up clicks
- if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) {
- return;
- }
- var pointerPoint = Unipointer.getPointerPoint( pointer );
- var boundingRect = this.tapElement.getBoundingClientRect();
- // standard or IE8 scroll positions
- var scrollX = isPageOffset ? window.pageXOffset : document.body.scrollLeft;
- var scrollY = isPageOffset ? window.pageYOffset : document.body.scrollTop;
- // calculate if pointer is inside tapElement
- var isInside = pointerPoint.x >= boundingRect.left + scrollX &&
- pointerPoint.x <= boundingRect.right + scrollX &&
- pointerPoint.y >= boundingRect.top + scrollY &&
- pointerPoint.y <= boundingRect.bottom + scrollY;
- // trigger callback if pointer is inside element
- if ( isInside ) {
- this.emitEvent( 'tap', [ event, pointer ] );
- }
- // set flag for emulated clicks 300ms after touchend
- if ( event.type != 'mouseup' ) {
- this.isIgnoringMouseUp = true;
- // reset flag after 300ms
- setTimeout( function() {
- delete this.isIgnoringMouseUp;
- }.bind( this ), 320 );
- }
- };
- TapListener.prototype.destroy = function() {
- this.pointerDone();
- this.unbindTap();
- };
- // ----- ----- //
- return TapListener;
- }));
- },{"unipointer":23}],22:[function(require,module,exports){
- /*!
- * Unidragger v1.1.5
- * Draggable base class
- * MIT license
- */
- /*jshint browser: true, unused: true, undef: true, strict: true */
- ( function( window, factory ) {
- /*global define: false, module: false, require: false */
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'eventie/eventie',
- 'unipointer/unipointer'
- ], function( eventie, Unipointer ) {
- return factory( window, eventie, Unipointer );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('eventie'),
- require('unipointer')
- );
- } else {
- // browser global
- window.Unidragger = factory(
- window,
- window.eventie,
- window.Unipointer
- );
- }
- }( window, function factory( window, eventie, Unipointer ) {
- 'use strict';
- // ----- ----- //
- function noop() {}
- // handle IE8 prevent default
- function preventDefaultEvent( event ) {
- if ( event.preventDefault ) {
- event.preventDefault();
- } else {
- event.returnValue = false;
- }
- }
- // -------------------------- Unidragger -------------------------- //
- function Unidragger() {}
- // inherit Unipointer & EventEmitter
- Unidragger.prototype = new Unipointer();
- // ----- bind start ----- //
- Unidragger.prototype.bindHandles = function() {
- this._bindHandles( true );
- };
- Unidragger.prototype.unbindHandles = function() {
- this._bindHandles( false );
- };
- var navigator = window.navigator;
- /**
- * works as unbinder, as you can .bindHandles( false ) to unbind
- * @param {Boolean} isBind - will unbind if falsey
- */
- Unidragger.prototype._bindHandles = function( isBind ) {
- // munge isBind, default to true
- isBind = isBind === undefined ? true : !!isBind;
- // extra bind logic
- var binderExtra;
- if ( navigator.pointerEnabled ) {
- binderExtra = function( handle ) {
- // disable scrolling on the element
- handle.style.touchAction = isBind ? 'none' : '';
- };
- } else if ( navigator.msPointerEnabled ) {
- binderExtra = function( handle ) {
- // disable scrolling on the element
- handle.style.msTouchAction = isBind ? 'none' : '';
- };
- } else {
- binderExtra = function() {
- // TODO re-enable img.ondragstart when unbinding
- if ( isBind ) {
- disableImgOndragstart( handle );
- }
- };
- }
- // bind each handle
- var bindMethod = isBind ? 'bind' : 'unbind';
- for ( var i=0, len = this.handles.length; i < len; i++ ) {
- var handle = this.handles[i];
- this._bindStartEvent( handle, isBind );
- binderExtra( handle );
- eventie[ bindMethod ]( handle, 'click', this );
- }
- };
- // remove default dragging interaction on all images in IE8
- // IE8 does its own drag thing on images, which messes stuff up
- function noDragStart() {
- return false;
- }
- // TODO replace this with a IE8 test
- var isIE8 = 'attachEvent' in document.documentElement;
- // IE8 only
- var disableImgOndragstart = !isIE8 ? noop : function( handle ) {
- if ( handle.nodeName == 'IMG' ) {
- handle.ondragstart = noDragStart;
- }
- var images = handle.querySelectorAll('img');
- for ( var i=0, len = images.length; i < len; i++ ) {
- var img = images[i];
- img.ondragstart = noDragStart;
- }
- };
- // ----- start event ----- //
- /**
- * pointer start
- * @param {Event} event
- * @param {Event or Touch} pointer
- */
- Unidragger.prototype.pointerDown = function( event, pointer ) {
- // dismiss range sliders
- if ( event.target.nodeName == 'INPUT' && event.target.type == 'range' ) {
- // reset pointerDown logic
- this.isPointerDown = false;
- delete this.pointerIdentifier;
- return;
- }
- this._dragPointerDown( event, pointer );
- // kludge to blur focused inputs in dragger
- var focused = document.activeElement;
- if ( focused && focused.blur ) {
- focused.blur();
- }
- // bind move and end events
- this._bindPostStartEvents( event );
- // track scrolling
- this.pointerDownScroll = Unidragger.getScrollPosition();
- eventie.bind( window, 'scroll', this );
- this.emitEvent( 'pointerDown', [ event, pointer ] );
- };
- // base pointer down logic
- Unidragger.prototype._dragPointerDown = function( event, pointer ) {
- // track to see when dragging starts
- this.pointerDownPoint = Unipointer.getPointerPoint( pointer );
- // prevent default, unless touchstart or <select>
- var isTouchstart = event.type == 'touchstart';
- var targetNodeName = event.target.nodeName;
- if ( !isTouchstart && targetNodeName != 'SELECT' ) {
- preventDefaultEvent( event );
- }
- };
- // ----- move event ----- //
- /**
- * drag move
- * @param {Event} event
- * @param {Event or Touch} pointer
- */
- Unidragger.prototype.pointerMove = function( event, pointer ) {
- var moveVector = this._dragPointerMove( event, pointer );
- this.emitEvent( 'pointerMove', [ event, pointer, moveVector ] );
- this._dragMove( event, pointer, moveVector );
- };
- // base pointer move logic
- Unidragger.prototype._dragPointerMove = function( event, pointer ) {
- var movePoint = Unipointer.getPointerPoint( pointer );
- var moveVector = {
- x: movePoint.x - this.pointerDownPoint.x,
- y: movePoint.y - this.pointerDownPoint.y
- };
- // start drag if pointer has moved far enough to start drag
- if ( !this.isDragging && this.hasDragStarted( moveVector ) ) {
- this._dragStart( event, pointer );
- }
- return moveVector;
- };
- // condition if pointer has moved far enough to start drag
- Unidragger.prototype.hasDragStarted = function( moveVector ) {
- return Math.abs( moveVector.x ) > 3 || Math.abs( moveVector.y ) > 3;
- };
- // ----- end event ----- //
- /**
- * pointer up
- * @param {Event} event
- * @param {Event or Touch} pointer
- */
- Unidragger.prototype.pointerUp = function( event, pointer ) {
- this.emitEvent( 'pointerUp', [ event, pointer ] );
- this._dragPointerUp( event, pointer );
- };
- Unidragger.prototype._dragPointerUp = function( event, pointer ) {
- if ( this.isDragging ) {
- this._dragEnd( event, pointer );
- } else {
- // pointer didn't move enough for drag to start
- this._staticClick( event, pointer );
- }
- };
- Unipointer.prototype.pointerDone = function() {
- eventie.unbind( window, 'scroll', this );
- };
- // -------------------------- drag -------------------------- //
- // dragStart
- Unidragger.prototype._dragStart = function( event, pointer ) {
- this.isDragging = true;
- this.dragStartPoint = Unidragger.getPointerPoint( pointer );
- // prevent clicks
- this.isPreventingClicks = true;
- this.dragStart( event, pointer );
- };
- Unidragger.prototype.dragStart = function( event, pointer ) {
- this.emitEvent( 'dragStart', [ event, pointer ] );
- };
- // dragMove
- Unidragger.prototype._dragMove = function( event, pointer, moveVector ) {
- // do not drag if not dragging yet
- if ( !this.isDragging ) {
- return;
- }
- this.dragMove( event, pointer, moveVector );
- };
- Unidragger.prototype.dragMove = function( event, pointer, moveVector ) {
- preventDefaultEvent( event );
- this.emitEvent( 'dragMove', [ event, pointer, moveVector ] );
- };
- // dragEnd
- Unidragger.prototype._dragEnd = function( event, pointer ) {
- // set flags
- this.isDragging = false;
- // re-enable clicking async
- var _this = this;
- setTimeout( function() {
- delete _this.isPreventingClicks;
- });
- this.dragEnd( event, pointer );
- };
- Unidragger.prototype.dragEnd = function( event, pointer ) {
- this.emitEvent( 'dragEnd', [ event, pointer ] );
- };
- Unidragger.prototype.pointerDone = function() {
- eventie.unbind( window, 'scroll', this );
- delete this.pointerDownScroll;
- };
- // ----- onclick ----- //
- // handle all clicks and prevent clicks when dragging
- Unidragger.prototype.onclick = function( event ) {
- if ( this.isPreventingClicks ) {
- preventDefaultEvent( event );
- }
- };
- // ----- staticClick ----- //
- // triggered after pointer down & up with no/tiny movement
- Unidragger.prototype._staticClick = function( event, pointer ) {
- // ignore emulated mouse up clicks
- if ( this.isIgnoringMouseUp && event.type == 'mouseup' ) {
- return;
- }
- // allow click in <input>s and <textarea>s
- var nodeName = event.target.nodeName;
- if ( nodeName == 'INPUT' || nodeName == 'TEXTAREA' ) {
- event.target.focus();
- }
- this.staticClick( event, pointer );
- // set flag for emulated clicks 300ms after touchend
- if ( event.type != 'mouseup' ) {
- this.isIgnoringMouseUp = true;
- var _this = this;
- // reset flag after 300ms
- setTimeout( function() {
- delete _this.isIgnoringMouseUp;
- }, 400 );
- }
- };
- Unidragger.prototype.staticClick = function( event, pointer ) {
- this.emitEvent( 'staticClick', [ event, pointer ] );
- };
- // ----- scroll ----- //
- Unidragger.prototype.onscroll = function() {
- var scroll = Unidragger.getScrollPosition();
- var scrollMoveX = this.pointerDownScroll.x - scroll.x;
- var scrollMoveY = this.pointerDownScroll.y - scroll.y;
- // cancel click/tap if scroll is too much
- if ( Math.abs( scrollMoveX ) > 3 || Math.abs( scrollMoveY ) > 3 ) {
- this._pointerDone();
- }
- };
- // ----- utils ----- //
- Unidragger.getPointerPoint = function( pointer ) {
- return {
- x: pointer.pageX !== undefined ? pointer.pageX : pointer.clientX,
- y: pointer.pageY !== undefined ? pointer.pageY : pointer.clientY
- };
- };
- var isPageOffset = window.pageYOffset !== undefined;
- // get scroll in { x, y }
- Unidragger.getScrollPosition = function() {
- return {
- x: isPageOffset ? window.pageXOffset : document.body.scrollLeft,
- y: isPageOffset ? window.pageYOffset : document.body.scrollTop
- };
- };
- // ----- ----- //
- Unidragger.getPointerPoint = Unipointer.getPointerPoint;
- return Unidragger;
- }));
- },{"eventie":7,"unipointer":23}],23:[function(require,module,exports){
- /*!
- * Unipointer v1.1.0
- * base class for doing one thing with pointer event
- * MIT license
- */
- /*jshint browser: true, undef: true, unused: true, strict: true */
- /*global define: false, module: false, require: false */
- ( function( window, factory ) {
- 'use strict';
- // universal module definition
- if ( typeof define == 'function' && define.amd ) {
- // AMD
- define( [
- 'eventEmitter/EventEmitter',
- 'eventie/eventie'
- ], function( EventEmitter, eventie ) {
- return factory( window, EventEmitter, eventie );
- });
- } else if ( typeof exports == 'object' ) {
- // CommonJS
- module.exports = factory(
- window,
- require('wolfy87-eventemitter'),
- require('eventie')
- );
- } else {
- // browser global
- window.Unipointer = factory(
- window,
- window.EventEmitter,
- window.eventie
- );
- }
- }( window, function factory( window, EventEmitter, eventie ) {
- 'use strict';
- function noop() {}
- function Unipointer() {}
- // inherit EventEmitter
- Unipointer.prototype = new EventEmitter();
- Unipointer.prototype.bindStartEvent = function( elem ) {
- this._bindStartEvent( elem, true );
- };
- Unipointer.prototype.unbindStartEvent = function( elem ) {
- this._bindStartEvent( elem, false );
- };
- /**
- * works as unbinder, as you can ._bindStart( false ) to unbind
- * @param {Boolean} isBind - will unbind if falsey
- */
- Unipointer.prototype._bindStartEvent = function( elem, isBind ) {
- // munge isBind, default to true
- isBind = isBind === undefined ? true : !!isBind;
- var bindMethod = isBind ? 'bind' : 'unbind';
- if ( window.navigator.pointerEnabled ) {
- // W3C Pointer Events, IE11. See https://coderwall.com/p/mfreca
- eventie[ bindMethod ]( elem, 'pointerdown', this );
- } else if ( window.navigator.msPointerEnabled ) {
- // IE10 Pointer Events
- eventie[ bindMethod ]( elem, 'MSPointerDown', this );
- } else {
- // listen for both, for devices like Chrome Pixel
- eventie[ bindMethod ]( elem, 'mousedown', this );
- eventie[ bindMethod ]( elem, 'touchstart', this );
- }
- };
- // trigger handler methods for events
- Unipointer.prototype.handleEvent = function( event ) {
- var method = 'on' + event.type;
- if ( this[ method ] ) {
- this[ method ]( event );
- }
- };
- // returns the touch that we're keeping track of
- Unipointer.prototype.getTouch = function( touches ) {
- for ( var i=0, len = touches.length; i < len; i++ ) {
- var touch = touches[i];
- if ( touch.identifier == this.pointerIdentifier ) {
- return touch;
- }
- }
- };
- // ----- start event ----- //
- Unipointer.prototype.onmousedown = function( event ) {
- // dismiss clicks from right or middle buttons
- var button = event.button;
- if ( button && ( button !== 0 && button !== 1 ) ) {
- return;
- }
- this._pointerDown( event, event );
- };
- Unipointer.prototype.ontouchstart = function( event ) {
- this._pointerDown( event, event.changedTouches[0] );
- };
- Unipointer.prototype.onMSPointerDown =
- Unipointer.prototype.onpointerdown = function( event ) {
- this._pointerDown( event, event );
- };
- /**
- * pointer start
- * @param {Event} event
- * @param {Event or Touch} pointer
- */
- Unipointer.prototype._pointerDown = function( event, pointer ) {
- // dismiss other pointers
- if ( this.isPointerDown ) {
- return;
- }
- this.isPointerDown = true;
- // save pointer identifier to match up touch events
- this.pointerIdentifier = pointer.pointerId !== undefined ?
- // pointerId for pointer events, touch.indentifier for touch events
- pointer.pointerId : pointer.identifier;
- this.pointerDown( event, pointer );
- };
- Unipointer.prototype.pointerDown = function( event, pointer ) {
- this._bindPostStartEvents( event );
- this.emitEvent( 'pointerDown', [ event, pointer ] );
- };
- // hash of events to be bound after start event
- var postStartEvents = {
- mousedown: [ 'mousemove', 'mouseup' ],
- touchstart: [ 'touchmove', 'touchend', 'touchcancel' ],
- pointerdown: [ 'pointermove', 'pointerup', 'pointercancel' ],
- MSPointerDown: [ 'MSPointerMove', 'MSPointerUp', 'MSPointerCancel' ]
- };
- Unipointer.prototype._bindPostStartEvents = function( event ) {
- if ( !event ) {
- return;
- }
- // get proper events to match start event
- var events = postStartEvents[ event.type ];
- // IE8 needs to be bound to document
- var node = event.preventDefault ? window : document;
- // bind events to node
- for ( var i=0, len = events.length; i < len; i++ ) {
- var evnt = events[i];
- eventie.bind( node, evnt, this );
- }
- // save these arguments
- this._boundPointerEvents = {
- events: events,
- node: node
- };
- };
- Unipointer.prototype._unbindPostStartEvents = function() {
- var args = this._boundPointerEvents;
- // IE8 can trigger dragEnd twice, check for _boundEvents
- if ( !args || !args.events ) {
- return;
- }
- for ( var i=0, len = args.events.length; i < len; i++ ) {
- var event = args.events[i];
- eventie.unbind( args.node, event, this );
- }
- delete this._boundPointerEvents;
- };
- // ----- move event ----- //
- Unipointer.prototype.onmousemove = function( event ) {
- this._pointerMove( event, event );
- };
- Unipointer.prototype.onMSPointerMove =
- Unipointer.prototype.onpointermove = function( event ) {
- if ( event.pointerId == this.pointerIdentifier ) {
- this._pointerMove( event, event );
- }
- };
- Unipointer.prototype.ontouchmove = function( event ) {
- var touch = this.getTouch( event.changedTouches );
- if ( touch ) {
- this._pointerMove( event, touch );
- }
- };
- /**
- * pointer move
- * @param {Event} event
- * @param {Event or Touch} pointer
- * @private
- */
- Unipointer.prototype._pointerMove = function( event, pointer ) {
- this.pointerMove( event, pointer );
- };
- // public
- Unipointer.prototype.pointerMove = function( event, pointer ) {
- this.emitEvent( 'pointerMove', [ event, pointer ] );
- };
- // ----- end event ----- //
- Unipointer.prototype.onmouseup = function( event ) {
- this._pointerUp( event, event );
- };
- Unipointer.prototype.onMSPointerUp =
- Unipointer.prototype.onpointerup = function( event ) {
- if ( event.pointerId == this.pointerIdentifier ) {
- this._pointerUp( event, event );
- }
- };
- Unipointer.prototype.ontouchend = function( event ) {
- var touch = this.getTouch( event.changedTouches );
- if ( touch ) {
- this._pointerUp( event, touch );
- }
- };
- /**
- * pointer up
- * @param {Event} event
- * @param {Event or Touch} pointer
- * @private
- */
- Unipointer.prototype._pointerUp = function( event, pointer ) {
- this._pointerDone();
- this.pointerUp( event, pointer );
- };
- // public
- Unipointer.prototype.pointerUp = function( event, pointer ) {
- this.emitEvent( 'pointerUp', [ event, pointer ] );
- };
- // ----- pointer done ----- //
- // triggered on pointer up & pointer cancel
- Unipointer.prototype._pointerDone = function() {
- // reset properties
- this.isPointerDown = false;
- delete this.pointerIdentifier;
- // remove events
- this._unbindPostStartEvents();
- this.pointerDone();
- };
- Unipointer.prototype.pointerDone = noop;
- // ----- pointer cancel ----- //
- Unipointer.prototype.onMSPointerCancel =
- Unipointer.prototype.onpointercancel = function( event ) {
- if ( event.pointerId == this.pointerIdentifier ) {
- this._pointerCancel( event, event );
- }
- };
- Unipointer.prototype.ontouchcancel = function( event ) {
- var touch = this.getTouch( event.changedTouches );
- if ( touch ) {
- this._pointerCancel( event, touch );
- }
- };
- /**
- * pointer cancel
- * @param {Event} event
- * @param {Event or Touch} pointer
- * @private
- */
- Unipointer.prototype._pointerCancel = function( event, pointer ) {
- this._pointerDone();
- this.pointerCancel( event, pointer );
- };
- // public
- Unipointer.prototype.pointerCancel = function( event, pointer ) {
- this.emitEvent( 'pointerCancel', [ event, pointer ] );
- };
- // ----- ----- //
- // utility function for getting x/y cooridinates from event, because IE8
- Unipointer.getPointerPoint = function( pointer ) {
- return {
- x: pointer.pageX !== undefined ? pointer.pageX : pointer.clientX,
- y: pointer.pageY !== undefined ? pointer.pageY : pointer.clientY
- };
- };
- // ----- ----- //
- return Unipointer;
- }));
- },{"eventie":7,"wolfy87-eventemitter":24}],24:[function(require,module,exports){
- /*!
- * EventEmitter v4.2.11 - git.io/ee
- * Unlicense - http://unlicense.org/
- * Oliver Caldwell - http://oli.me.uk/
- * @preserve
- */
- ;(function () {
- 'use strict';
- /**
- * Class for managing events.
- * Can be extended to provide event functionality in other classes.
- *
- * @class EventEmitter Manages event registering and emitting.
- */
- function EventEmitter() {}
- // Shortcuts to improve speed and size
- var proto = EventEmitter.prototype;
- var exports = this;
- var originalGlobalValue = exports.EventEmitter;
- /**
- * Finds the index of the listener for the event in its storage array.
- *
- * @param {Function[]} listeners Array of listeners to search through.
- * @param {Function} listener Method to look for.
- * @return {Number} Index of the specified listener, -1 if not found
- * @api private
- */
- function indexOfListener(listeners, listener) {
- var i = listeners.length;
- while (i--) {
- if (listeners[i].listener === listener) {
- return i;
- }
- }
- return -1;
- }
- /**
- * Alias a method while keeping the context correct, to allow for overwriting of target method.
- *
- * @param {String} name The name of the target method.
- * @return {Function} The aliased method
- * @api private
- */
- function alias(name) {
- return function aliasClosure() {
- return this[name].apply(this, arguments);
- };
- }
- /**
- * Returns the listener array for the specified event.
- * Will initialise the event object and listener arrays if required.
- * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
- * Each property in the object response is an array of listener functions.
- *
- * @param {String|RegExp} evt Name of the event to return the listeners from.
- * @return {Function[]|Object} All listener functions for the event.
- */
- proto.getListeners = function getListeners(evt) {
- var events = this._getEvents();
- var response;
- var key;
- // Return a concatenated array of all matching events if
- // the selector is a regular expression.
- if (evt instanceof RegExp) {
- response = {};
- for (key in events) {
- if (events.hasOwnProperty(key) && evt.test(key)) {
- response[key] = events[key];
- }
- }
- }
- else {
- response = events[evt] || (events[evt] = []);
- }
- return response;
- };
- /**
- * Takes a list of listener objects and flattens it into a list of listener functions.
- *
- * @param {Object[]} listeners Raw listener objects.
- * @return {Function[]} Just the listener functions.
- */
- proto.flattenListeners = function flattenListeners(listeners) {
- var flatListeners = [];
- var i;
- for (i = 0; i < listeners.length; i += 1) {
- flatListeners.push(listeners[i].listener);
- }
- return flatListeners;
- };
- /**
- * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
- *
- * @param {String|RegExp} evt Name of the event to return the listeners from.
- * @return {Object} All listener functions for an event in an object.
- */
- proto.getListenersAsObject = function getListenersAsObject(evt) {
- var listeners = this.getListeners(evt);
- var response;
- if (listeners instanceof Array) {
- response = {};
- response[evt] = listeners;
- }
- return response || listeners;
- };
- /**
- * Adds a listener function to the specified event.
- * The listener will not be added if it is a duplicate.
- * If the listener returns true then it will be removed after it is called.
- * If you pass a regular expression as the event name then the listener will be added to all events that match it.
- *
- * @param {String|RegExp} evt Name of the event to attach the listener to.
- * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.addListener = function addListener(evt, listener) {
- var listeners = this.getListenersAsObject(evt);
- var listenerIsWrapped = typeof listener === 'object';
- var key;
- for (key in listeners) {
- if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
- listeners[key].push(listenerIsWrapped ? listener : {
- listener: listener,
- once: false
- });
- }
- }
- return this;
- };
- /**
- * Alias of addListener
- */
- proto.on = alias('addListener');
- /**
- * Semi-alias of addListener. It will add a listener that will be
- * automatically removed after its first execution.
- *
- * @param {String|RegExp} evt Name of the event to attach the listener to.
- * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.addOnceListener = function addOnceListener(evt, listener) {
- return this.addListener(evt, {
- listener: listener,
- once: true
- });
- };
- /**
- * Alias of addOnceListener.
- */
- proto.once = alias('addOnceListener');
- /**
- * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
- * You need to tell it what event names should be matched by a regex.
- *
- * @param {String} evt Name of the event to create.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.defineEvent = function defineEvent(evt) {
- this.getListeners(evt);
- return this;
- };
- /**
- * Uses defineEvent to define multiple events.
- *
- * @param {String[]} evts An array of event names to define.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.defineEvents = function defineEvents(evts) {
- for (var i = 0; i < evts.length; i += 1) {
- this.defineEvent(evts[i]);
- }
- return this;
- };
- /**
- * Removes a listener function from the specified event.
- * When passed a regular expression as the event name, it will remove the listener from all events that match it.
- *
- * @param {String|RegExp} evt Name of the event to remove the listener from.
- * @param {Function} listener Method to remove from the event.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.removeListener = function removeListener(evt, listener) {
- var listeners = this.getListenersAsObject(evt);
- var index;
- var key;
- for (key in listeners) {
- if (listeners.hasOwnProperty(key)) {
- index = indexOfListener(listeners[key], listener);
- if (index !== -1) {
- listeners[key].splice(index, 1);
- }
- }
- }
- return this;
- };
- /**
- * Alias of removeListener
- */
- proto.off = alias('removeListener');
- /**
- * Adds listeners in bulk using the manipulateListeners method.
- * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
- * You can also pass it a regular expression to add the array of listeners to all events that match it.
- * Yeah, this function does quite a bit. That's probably a bad thing.
- *
- * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
- * @param {Function[]} [listeners] An optional array of listener functions to add.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.addListeners = function addListeners(evt, listeners) {
- // Pass through to manipulateListeners
- return this.manipulateListeners(false, evt, listeners);
- };
- /**
- * Removes listeners in bulk using the manipulateListeners method.
- * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
- * You can also pass it an event name and an array of listeners to be removed.
- * You can also pass it a regular expression to remove the listeners from all events that match it.
- *
- * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
- * @param {Function[]} [listeners] An optional array of listener functions to remove.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.removeListeners = function removeListeners(evt, listeners) {
- // Pass through to manipulateListeners
- return this.manipulateListeners(true, evt, listeners);
- };
- /**
- * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
- * The first argument will determine if the listeners are removed (true) or added (false).
- * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
- * You can also pass it an event name and an array of listeners to be added/removed.
- * You can also pass it a regular expression to manipulate the listeners of all events that match it.
- *
- * @param {Boolean} remove True if you want to remove listeners, false if you want to add.
- * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
- * @param {Function[]} [listeners] An optional array of listener functions to add/remove.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
- var i;
- var value;
- var single = remove ? this.removeListener : this.addListener;
- var multiple = remove ? this.removeListeners : this.addListeners;
- // If evt is an object then pass each of its properties to this method
- if (typeof evt === 'object' && !(evt instanceof RegExp)) {
- for (i in evt) {
- if (evt.hasOwnProperty(i) && (value = evt[i])) {
- // Pass the single listener straight through to the singular method
- if (typeof value === 'function') {
- single.call(this, i, value);
- }
- else {
- // Otherwise pass back to the multiple function
- multiple.call(this, i, value);
- }
- }
- }
- }
- else {
- // So evt must be a string
- // And listeners must be an array of listeners
- // Loop over it and pass each one to the multiple method
- i = listeners.length;
- while (i--) {
- single.call(this, evt, listeners[i]);
- }
- }
- return this;
- };
- /**
- * Removes all listeners from a specified event.
- * If you do not specify an event then all listeners will be removed.
- * That means every event will be emptied.
- * You can also pass a regex to remove all events that match it.
- *
- * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.removeEvent = function removeEvent(evt) {
- var type = typeof evt;
- var events = this._getEvents();
- var key;
- // Remove different things depending on the state of evt
- if (type === 'string') {
- // Remove all listeners for the specified event
- delete events[evt];
- }
- else if (evt instanceof RegExp) {
- // Remove all events matching the regex.
- for (key in events) {
- if (events.hasOwnProperty(key) && evt.test(key)) {
- delete events[key];
- }
- }
- }
- else {
- // Remove all listeners in all events
- delete this._events;
- }
- return this;
- };
- /**
- * Alias of removeEvent.
- *
- * Added to mirror the node API.
- */
- proto.removeAllListeners = alias('removeEvent');
- /**
- * Emits an event of your choice.
- * When emitted, every listener attached to that event will be executed.
- * If you pass the optional argument array then those arguments will be passed to every listener upon execution.
- * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
- * So they will not arrive within the array on the other side, they will be separate.
- * You can also pass a regular expression to emit to all events that match it.
- *
- * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
- * @param {Array} [args] Optional array of arguments to be passed to each listener.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.emitEvent = function emitEvent(evt, args) {
- var listeners = this.getListenersAsObject(evt);
- var listener;
- var i;
- var key;
- var response;
- for (key in listeners) {
- if (listeners.hasOwnProperty(key)) {
- i = listeners[key].length;
- while (i--) {
- // If the listener returns true then it shall be removed from the event
- // The function is executed either with a basic call or an apply if there is an args array
- listener = listeners[key][i];
- if (listener.once === true) {
- this.removeListener(evt, listener.listener);
- }
- response = listener.listener.apply(this, args || []);
- if (response === this._getOnceReturnValue()) {
- this.removeListener(evt, listener.listener);
- }
- }
- }
- }
- return this;
- };
- /**
- * Alias of emitEvent
- */
- proto.trigger = alias('emitEvent');
- /**
- * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
- * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
- *
- * @param {String|RegExp} evt Name of the event to emit and execute listeners for.
- * @param {...*} Optional additional arguments to be passed to each listener.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.emit = function emit(evt) {
- var args = Array.prototype.slice.call(arguments, 1);
- return this.emitEvent(evt, args);
- };
- /**
- * Sets the current value to check against when executing listeners. If a
- * listeners return value matches the one set here then it will be removed
- * after execution. This value defaults to true.
- *
- * @param {*} value The new value to check for when executing listeners.
- * @return {Object} Current instance of EventEmitter for chaining.
- */
- proto.setOnceReturnValue = function setOnceReturnValue(value) {
- this._onceReturnValue = value;
- return this;
- };
- /**
- * Fetches the current value to check against when executing listeners. If
- * the listeners return value matches this one then it should be removed
- * automatically. It will return true by default.
- *
- * @return {*|Boolean} The current value to check for or the default, true.
- * @api private
- */
- proto._getOnceReturnValue = function _getOnceReturnValue() {
- if (this.hasOwnProperty('_onceReturnValue')) {
- return this._onceReturnValue;
- }
- else {
- return true;
- }
- };
- /**
- * Fetches the events object and creates one if required.
- *
- * @return {Object} The events storage object.
- * @api private
- */
- proto._getEvents = function _getEvents() {
- return this._events || (this._events = {});
- };
- /**
- * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
- *
- * @return {Function} Non conflicting EventEmitter class.
- */
- EventEmitter.noConflict = function noConflict() {
- exports.EventEmitter = originalGlobalValue;
- return EventEmitter;
- };
- // Expose the class either via AMD, CommonJS or the global object
- if (typeof define === 'function' && define.amd) {
- define(function () {
- return EventEmitter;
- });
- }
- else if (typeof module === 'object' && module.exports){
- module.exports = EventEmitter;
- }
- else {
- exports.EventEmitter = EventEmitter;
- }
- }.call(this));
- },{}]},{},[1]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement