1/*! 2 * skrollr core 3 * 4 * Alexander Prinzhorn - https://github.com/Prinzhorn/skrollr 5 * 6 * Free to use under terms of MIT license 7 */ 8(function(window, document, undefined) { 9 'use strict'; 10 11 /* 12 * Global api. 13 */ 14 var skrollr = { 15 get: function() { 16 return _instance; 17 }, 18 //Main entry point. 19 init: function(options) { 20 return _instance || new Skrollr(options); 21 }, 22 VERSION: '0.6.29' 23 }; 24 25 //Minify optimization. 26 var hasProp = Object.prototype.hasOwnProperty; 27 var Math = window.Math; 28 var getStyle = window.getComputedStyle; 29 30 //They will be filled when skrollr gets initialized. 31 var documentElement; 32 var body; 33 34 var EVENT_TOUCHSTART = 'touchstart'; 35 var EVENT_TOUCHMOVE = 'touchmove'; 36 var EVENT_TOUCHCANCEL = 'touchcancel'; 37 var EVENT_TOUCHEND = 'touchend'; 38 39 var SKROLLABLE_CLASS = 'skrollable'; 40 var SKROLLABLE_BEFORE_CLASS = SKROLLABLE_CLASS + '-before'; 41 var SKROLLABLE_BETWEEN_CLASS = SKROLLABLE_CLASS + '-between'; 42 var SKROLLABLE_AFTER_CLASS = SKROLLABLE_CLASS + '-after'; 43 44 var SKROLLR_CLASS = 'skrollr'; 45 var NO_SKROLLR_CLASS = 'no-' + SKROLLR_CLASS; 46 var SKROLLR_DESKTOP_CLASS = SKROLLR_CLASS + '-desktop'; 47 var SKROLLR_MOBILE_CLASS = SKROLLR_CLASS + '-mobile'; 48 49 var DEFAULT_EASING = 'linear'; 50 var DEFAULT_DURATION = 1000;//ms 51 var DEFAULT_MOBILE_DECELERATION = 0.004;//pixel/ms² 52 53 var DEFAULT_SKROLLRBODY = 'skrollr-body'; 54 55 var DEFAULT_SMOOTH_SCROLLING_DURATION = 200;//ms 56 57 var ANCHOR_START = 'start'; 58 var ANCHOR_END = 'end'; 59 var ANCHOR_CENTER = 'center'; 60 var ANCHOR_BOTTOM = 'bottom'; 61 62 //The property which will be added to the DOM element to hold the ID of the skrollable. 63 var SKROLLABLE_ID_DOM_PROPERTY = '___skrollable_id'; 64 65 var rxTouchIgnoreTags = /^(?:input|textarea|button|select)$/i; 66 67 var rxTrim = /^\s+|\s+$/g; 68 69 //Find all data-attributes. data-[_constant]-[offset]-[anchor]-[anchor]. 70 var rxKeyframeAttribute = /^data(?:-(_\w+))?(?:-?(-?\d*\.?\d+p?))?(?:-?(start|end|top|center|bottom))?(?:-?(top|center|bottom))?$/; 71 72 var rxPropValue = /\s*(@?[\w\-\[\]]+)\s*:\s*(.+?)\s*(?:;|$)/gi; 73 74 //Easing function names follow the property in square brackets. 75 var rxPropEasing = /^(@?[a-z\-]+)\[(\w+)\]$/; 76 77 var rxCamelCase = /-([a-z0-9_])/g; 78 var rxCamelCaseFn = function(str, letter) { 79 return letter.toUpperCase(); 80 }; 81 82 //Numeric values with optional sign.
83 var rxNumericValue = /[\-+]?[\d]*\.?[\d]+/g; 84 85 //Used to replace occurences of {?} with a number. 86 var rxInterpolateString = /\{\?\}/g; 87 88 //Finds rgb(a) colors, which don't use the percentage notation. 89 var rxRGBAIntegerColor = /rgba?\(\s*-?\d+\s*,\s*-?\d+\s*,\s*-?\d+/g; 90 91 //Finds all gradients. 92 var rxGradient = /[a-z\-]+-gradient/g; 93 94 //Vendor prefix. Will be set once skrollr gets initialized. 95 var theCSSPrefix = ''; 96 var theDashedCSSPrefix = ''; 97 98 //Will be called once (when skrollr gets initialized). 99 var detectCSSPrefix = function() { 100 //Only relevant prefixes. May be extended. 101 //Could be dangerous if there will ever be a CSS property which actually starts with "ms". Don't hope so. 102 var rxPrefixes = /^(?:O|Moz|webkit|ms)|(?:-(?:o|moz|webkit|ms)-)/; 103 104 //Detect prefix for current browser by finding the first property using a prefix. 105 if(!getStyle) { 106 return; 107 } 108 109 var style = getStyle(body, null); 110 111 for(var k in style) { 112 //We check the key and if the key is a number, we check the value as well, because safari's getComputedStyle returns some weird array-like thingy. 113 theCSSPrefix = (k.match(rxPrefixes) || (+k == k && style[k].match(rxPrefixes))); 114 115 if(theCSSPrefix) { 116 break; 117 } 118 } 119 120 //Did we even detect a prefix? 121 if(!theCSSPrefix) { 122 theCSSPrefix = theDashedCSSPrefix = ''; 123 124 return; 125 } 126 127 theCSSPrefix = theCSSPrefix[0]; 128 129 //We could have detected either a dashed prefix or this camelCaseish-inconsistent stuff. 130 if(theCSSPrefix.slice(0,1) === '-') { 131 theDashedCSSPrefix = theCSSPrefix; 132 133 //There's no logic behind these. Need a look up. 134 theCSSPrefix = ({ 135 '-webkit-': 'webkit', 136 '-moz-': 'Moz', 137 '-ms-': 'ms', 138 '-o-': 'O' 139 })[theCSSPrefix]; 140 } else { 141 theDashedCSSPrefix = '-' + theCSSPrefix.toLowerCase() + '-'; 142 } 143 }; 144 145 var polyfillRAF = function() { 146 var requestAnimFrame = window.requestAnimationFrame || window[theCSSPrefix.toLowerCase() + 'RequestAnimationFrame']; 147 148 var lastTime = _now(); 149 150 if(_isMobile || !requestAnimFrame) { 151 requestAnimFrame = function(callback) { 152 //How long did it take to render? 153 var deltaTime = _now() - lastTime; 154 var delay = Math.max(0, 1000 / 60 - deltaTime); 155 156 return window.setTimeout(function() { 157 lastTime = _now(); 158 callback(); 159 }, delay); 160 }; 161 } 162 163 return requestAnimFrame; 164 }; 165 166 var polyfillCAF = function() { 167 var cancelAnimFrame = window.cancelAnimationFrame || window[theCSSPrefix.toLowerCase() + 'CancelAnimationFrame']; 168 169 if(_isMobile || !cancelAnimFrame) { 170 cancelAnimFrame = function(timeout) { 171 return window.clearTimeout(timeout); 172 }; 173 } 174 175 return cancelAnimFrame; 176 }; 177 178 //Built-in easing functions. 179 var easings = { 180 begin: function() { 181 return 0; 182 }, 183 end: function() { 184 return 1; 185 }, 186 linear: function(p) { 187 return p; 188 }, 189 quadratic: function(p) { 190 return p * p; 191 }, 192 cubic: function(p) { 193 return p * p * p; 194 }, 195 swing: function(p) { 196 return (-Math.cos(p * Math.PI) / 2) + 0.5; 197 }, 198 sqrt: function(p) { 199 return Math.sqrt(p); 200 }, 201 outCubic: function(p) { 202 return (Math.pow((p - 1), 3) + 1); 203 }, 204 //see https://www.desmos.com/calculator/tbr20s8vd2 for how I did this 205 bounce: function(p) { 206 var a; 207 208 if(p <= 0.5083) { 209 a = 3; 210 } else if(p <= 0.8489) { 211 a = 9; 212 } else if(p <= 0.96208) { 213 a = 27; 214 } else if(p <= 0.99981) { 215 a = 91; 216 } else { 217 return 1; 218 } 219 220 return 1 - Math.abs(3 * Math.cos(p * a * 1.028) / a); 221 } 222 }; 223 224 /** 225 * Constructor. 226 */ 227 function Skrollr(options) { 228 documentElement = document.documentElement; 229 body = document.body; 230 231 detectCSSPrefix(); 232 233 _instance = this; 234 235 options = options || {}; 236 237 _constants = options.constants || {}; 238 239 //We allow defining custom easings or overwrite existing. 240 if(options.easing) { 241 for(var e in options.easing) { 242 easings[e] = options.easing[e]; 243 } 244 } 245 246 _edgeStrategy = options.edgeStrategy || 'set'; 247 248 _listeners = { 249 //Function to be called right before rendering. 250 beforerender: options.beforerender, 251 252 //Function to be called right after finishing rendering. 253 render: options.render, 254 255 //Function to be called whenever an element with the `data-emit-events` attribute passes a keyframe. 256 keyframe: options.keyframe 257 }; 258 259 //forceHeight is true by default 260 _forceHeight = options.forceHeight !== false; 261 262 if(_forceHeight) { 263 _scale = options.scale || 1; 264 } 265 266 _mobileDeceleration = options.mobileDeceleration || DEFAULT_MOBILE_DECELERATION; 267 268 _smoothScrollingEnabled = options.smoothScrolling !== false; 269 _smoothScrollingDuration = options.smoothScrollingDuration || DEFAULT_SMOOTH_SCROLLING_DURATION; 270 271 //Dummy object. Will be overwritten in the _render method when smooth scrolling is calculated. 272 _smoothScrolling = { 273 targetTop: _instance.getScrollTop() 274 }; 275 276 //A custom check function may be passed. 277 _isMobile = ((options.mobileCheck || function() { 278 return (/Android|iPhone|iPad|iPod|BlackBerry/i).test(navigator.userAgent || navigator.vendor || window.opera); 279 })()); 280 281 if(_isMobile) { 282 _skrollrBody = document.getElementById(options.skrollrBody || DEFAULT_SKROLLRBODY); 283 284 //Detect 3d transform if there's a skrollr-body (only needed for #skrollr-body). 285 if(_skrollrBody) { 286 _detect3DTransforms(); 287 } 288 289 _initMobile();
290 _updateClass(documentElement, [SKROLLR_CLASS, SKROLLR_MOBILE_CLASS], [NO_SKROLLR_CLASS]); 291 } else { 292 _updateClass(documentElement, [SKROLLR_CLASS, SKROLLR_DESKTOP_CLASS], [NO_SKROLLR_CLASS]); 293 } 294 295 //Triggers parsing of elements and a first reflow. 296 _instance.refresh(); 297 298 _addEvent(window, 'resize orientationchange', function() { 299 var width = documentElement.clientWidth; 300 var height = documentElement.clientHeight; 301 302 //Only reflow if the size actually changed (#271). 303 if(height !== _lastViewportHeight || width !== _lastViewportWidth) { 304 _lastViewportHeight = height; 305 _lastViewportWidth = width; 306 307 _requestReflow = true; 308 } 309 }); 310 311 var requestAnimFrame = polyfillRAF(); 312 313 //Let's go. 314 (function animloop(){ 315 _render(); 316 _animFrame = requestAnimFrame(animloop); 317 }()); 318 319 return _instance; 320 } 321 322 /** 323 * (Re)parses some or all elements. 324 */ 325 Skrollr.prototype.refresh = function(elements) { 326 var elementIndex; 327 var elementsLength; 328 var ignoreID = false; 329 330 //Completely reparse anything without argument. 331 if(elements === undefined) { 332 //Ignore that some elements may already have a skrollable ID. 333 ignoreID = true; 334 335 _skrollables = []; 336 _skrollableIdCounter = 0; 337 338 elements = document.getElementsByTagName('*'); 339 } else if(elements.length === undefined) { 340 //We also accept a single element as parameter. 341 elements = [elements]; 342 } 343 344 elementIndex = 0; 345 elementsLength = elements.length; 346 347 for(; elementIndex < elementsLength; elementIndex++) { 348 var el = elements[elementIndex]; 349 var anchorTarget = el; 350 var keyFrames = []; 351 352 //If this particular element should be smooth scrolled. 353 var smoothScrollThis = _smoothScrollingEnabled; 354 355 //The edge strategy for this particular element. 356 var edgeStrategy = _edgeStrategy; 357 358 //If this particular element should emit keyframe events. 359 var emitEvents = false; 360 361 //If we're reseting the counter, remove any old element ids that may be hanging around. 362 if(ignoreID && SKROLLABLE_ID_DOM_PROPERTY in el) { 363 delete el[SKROLLABLE_ID_DOM_PROPERTY]; 364 } 365 366 if(!el.attributes) { 367 continue; 368 } 369 370 //Iterate over all attributes and search for key frame attributes. 371 var attributeIndex = 0; 372 var attributesLength = el.attributes.length; 373 374 for (; attributeIndex < attributesLength; attributeIndex++) { 375 var attr = el.attributes[attributeIndex]; 376 377 if(attr.name === 'data-anchor-target') { 378 anchorTarget = document.querySelector(attr.value); 379 380 if(anchorTarget === null) { 381 throw 'Unable to find anchor target "' + attr.value + '"'; 382 } 383 384 continue; 385 } 386 387 //Global smooth scrolling can be overridden by the element attribute. 388 if(attr.name === 'data-smooth-scrolling') { 389 smoothScrollThis = attr.value !== 'off'; 390 391 continue; 392 } 393 394 //Global edge strategy can be overridden by the element attribute. 395 if(attr.name === 'data-edge-strategy') { 396 edgeStrategy = attr.value; 397 398 continue; 399 } 400 401 //Is this element tagged with the `data-emit-events` attribute? 402 if(attr.name === 'data-emit-events') { 403 emitEvents = true; 404 405 continue; 406 } 407 408 var match = attr.name.match(rxKeyframeAttribute); 409 410 if(match === null) { 411 continue; 412 } 413 414 var kf = { 415 props: attr.value, 416 //Point back to the element as well. 417 element: el, 418 //The name of the event which this keyframe will fire, if emitEvents is 419 eventType: attr.name.replace(rxCamelCase, rxCamelCaseFn) 420 }; 421 422 keyFrames.push(kf); 423 424 var constant = match[1]; 425 426 if(constant) { 427 //Strip the underscore prefix. 428 kf.constant = constant.substr(1); 429 } 430 431 //Get the key frame offset. 432 var offset = match[2]; 433 434 //Is it a percentage offset? 435 if(/p$/.test(offset)) { 436 kf.isPercentage = true; 437 kf.offset = (offset.slice(0, -1) | 0) / 100; 438 } else { 439 kf.offset = (offset | 0); 440 } 441 442 var anchor1 = match[3]; 443 444 //If second anchor is not set, the first will be taken for both. 445 var anchor2 = match[4] || anchor1; 446 447 //"absolute" (or "classic") mode, where numbers mean absolute scroll offset. 448 if(!anchor1 || anchor1 === ANCHOR_START || anchor1 === ANCHOR_END) { 449 kf.mode = 'absolute'; 450 451 //data-end needs to be calculated after all key frames are known. 452 if(anchor1 === ANCHOR_END) { 453 kf.isEnd = true; 454 } else if(!kf.isPercentage) {
455 //For data-start we can already set the key frame w/o calculations. 456 //#59: "scale" options should only affect absolute mode. 457 kf.offset = kf.offset * _scale; 458 } 459 } 460 //"relative" mode, where numbers are relative to anchors. 461 else { 462 kf.mode = 'relative'; 463 kf.anchors = [anchor1, anchor2]; 464 } 465 } 466 467 //Does this element have key frames? 468 if(!keyFrames.length) { 469 continue; 470 } 471 472 //Will hold the original style and class attributes before we controlled the element (see #80). 473 var styleAttr, classAttr; 474 475 var id; 476 477 if(!ignoreID && SKROLLABLE_ID_DOM_PROPERTY in el) { 478 //We already have this element under control. Grab the corresponding skrollable id. 479 id = el[SKROLLABLE_ID_DOM_PROPERTY]; 480 styleAttr = _skrollables[id].styleAttr; 481 classAttr = _skrollables[id].classAttr; 482 } else { 483 //It's an unknown element. Asign it a new skrollable id. 484 id = (el[SKROLLABLE_ID_DOM_PROPERTY] = _skrollableIdCounter++); 485 styleAttr = el.style.cssText; 486 classAttr = _getClass(el); 487 } 488 489 _skrollables[id] = { 490 element: el, 491 styleAttr: styleAttr, 492 classAttr: classAttr, 493 anchorTarget: anchorTarget, 494 keyFrames: keyFrames, 495 smoothScrolling: smoothScrollThis, 496 edgeStrategy: edgeStrategy, 497 emitEvents: emitEvents, 498 lastFrameIndex: -1 499 }; 500 501 _updateClass(el, [SKROLLABLE_CLASS], []); 502 } 503 504 //Reflow for the first time. 505 _reflow(); 506 507 //Now that we got all key frame numbers right, actually parse the properties. 508 elementIndex = 0; 509 elementsLength = elements.length; 510 511 for(; elementIndex < elementsLength; elementIndex++) { 512 var sk = _skrollables[elements[elementIndex][SKROLLABLE_ID_DOM_PROPERTY]]; 513 514 if(sk === undefined) { 515 continue; 516 } 517 518 //Parse the property string to objects 519 _parseProps(sk); 520 521 //Fill key frames with missing properties from left and right 522 _fillProps(sk); 523 } 524 525 return _instance; 526 }; 527 528 /** 529 * Transform "relative" mode to "absolute" mode. 530 * That is, calculate anchor position and offset of element. 531 */ 532 Skrollr.prototype.relativeToAbsolute = function(element, viewportAnchor, elementAnchor) { 533 var viewportHeight = documentElement.clientHeight; 534 var box = element.getBoundingClientRect(); 535 var absolute = box.top; 536 537 //#100: IE doesn't supply "height" with getBoundingClientRect. 538 var boxHeight = box.bottom - box.top; 539 540 if(viewportAnchor === ANCHOR_BOTTOM) { 541 absolute -= viewportHeight; 542 } else if(viewportAnchor === ANCHOR_CENTER) { 543 absolute -= viewportHeight / 2; 544 } 545 546 if(elementAnchor === ANCHOR_BOTTOM) { 547 absolute += boxHeight; 548 } else if(elementAnchor === ANCHOR_CENTER) { 549 absolute += boxHeight / 2; 550 } 551 552 //Compensate scrolling since getBoundingClientRect is relative to viewport. 553 absolute += _instance.getScrollTop(); 554 555 return (absolute + 0.5) | 0; 556 }; 557 558 /** 559 * Animates scroll top to new position. 560 */ 561 Skrollr.prototype.animateTo = function(top, options) { 562 options = options || {}; 563 564 var now = _now(); 565 var scrollTop = _instance.getScrollTop(); 566 567 //Setting this to a new value will automatically cause the current animation to stop, if any. 568 _scrollAnimation = { 569 startTop: scrollTop, 570 topDiff: top - scrollTop, 571 targetTop: top, 572 duration: options.duration || DEFAULT_DURATION, 573 startTime: now, 574 endTime: now + (options.duration || DEFAULT_DURATION), 575 easing: easings[options.easing || DEFAULT_EASING], 576 done: options.done 577 }; 578 579 //Don't queue the animation if there's nothing to animate. 580 if(!_scrollAnimation.topDiff) { 581 if(_scrollAnimation.done) { 582 _scrollAnimation.done.call(_instance, false); 583 } 584 585 _scrollAnimation = undefined; 586 } 587 588 return _instance; 589 }; 590 591 /** 592 * Stops animateTo animation. 593 */ 594 Skrollr.prototype.stopAnimateTo = function() { 595 if(_scrollAnimation && _scrollAnimation.done) { 596 _scrollAnimation.done.call(_instance, true); 597 } 598 599 _scrollAnimation = undefined; 600 }; 601 602 /** 603 * Returns if an animation caused by animateTo is currently running. 604 */ 605 Skrollr.prototype.isAnimatingTo = function() { 606 return !!_scrollAnimation; 607 }; 608 609 Skrollr.prototype.isMobile = function() { 610 return _isMobile; 611 }; 612 613 Skrollr.prototype.setScrollTop = function(top, force) { 614 _forceRender = (force === true); 615 616 if(_isMobile) { 617 _mobileOffset = Math.min(Math.max(top, 0), _maxKeyFrame); 618 } else { 619 window.scrollTo(0, top); 620 } 621 622 return _instance; 623 }; 624 625 Skrollr.prototype.getScrollTop = function() { 626 if(_isMobile) { 627 return _mobileOffset; 628 } else { 629 return window.pageYOffset || documentElement.scrollTop || body.scrollTop || 0; 630 } 631 }; 632 633 Skrollr.prototype.getMaxScrollTop = function() { 634 return _maxKeyFrame; 635 }; 636 637 Skrollr.prototype.on = function(name, fn) { 638 _listeners[name] = fn; 639 640 return _instance; 641 }; 642 643 Skrollr.prototype.off = function(name) { 644 delete _listeners[name]; 645 646 return _instance; 647 }; 648 649 Skrollr.prototype.destroy = function() { 650 var cancelAnimFrame = polyfillCAF();
651 cancelAnimFrame(_animFrame); 652 _removeAllEvents(); 653 654 _updateClass(documentElement, [NO_SKROLLR_CLASS], [SKROLLR_CLASS, SKROLLR_DESKTOP_CLASS, SKROLLR_MOBILE_CLASS]); 655 656 var skrollableIndex = 0; 657 var skrollablesLength = _skrollables.length; 658 659 for(; skrollableIndex < skrollablesLength; skrollableIndex++) { 660 _reset(_skrollables[skrollableIndex].element); 661 } 662 663 documentElement.style.overflow = body.style.overflow = ''; 664 documentElement.style.height = body.style.height = ''; 665 666 if(_skrollrBody) { 667 skrollr.setStyle(_skrollrBody, 'transform', 'none'); 668 } 669 670 _instance = undefined; 671 _skrollrBody = undefined; 672 _listeners = undefined; 673 _forceHeight = undefined; 674 _maxKeyFrame = 0; 675 _scale = 1; 676 _constants = undefined; 677 _mobileDeceleration = undefined; 678 _direction = 'down'; 679 _lastTop = -1; 680 _lastViewportWidth = 0; 681 _lastViewportHeight = 0; 682 _requestReflow = false; 683 _scrollAnimation = undefined; 684 _smoothScrollingEnabled = undefined; 685 _smoothScrollingDuration = undefined; 686 _smoothScrolling = undefined; 687 _forceRender = undefined; 688 _skrollableIdCounter = 0; 689 _edgeStrategy = undefined; 690 _isMobile = false; 691 _mobileOffset = 0; 692 _translateZ = undefined; 693 }; 694 695 /* 696 Private methods. 697 */ 698 699 var _initMobile = function() { 700 var initialElement; 701 var initialTouchY; 702 var initialTouchX; 703 var currentElement; 704 var currentTouchY; 705 var currentTouchX; 706 var lastTouchY; 707 var deltaY; 708 709 var initialTouchTime; 710 var currentTouchTime; 711 var lastTouchTime; 712 var deltaTime; 713 714 _addEvent(documentElement, [EVENT_TOUCHSTART, EVENT_TOUCHMOVE, EVENT_TOUCHCANCEL, EVENT_TOUCHEND].join(' '), function(e) { 715 var touch = e.changedTouches[0]; 716 717 currentElement = e.target; 718 719 //We don't want text nodes. 720 while(currentElement.nodeType === 3) { 721 currentElement = currentElement.parentNode; 722 } 723 724 currentTouchY = touch.clientY; 725 currentTouchX = touch.clientX; 726 currentTouchTime = e.timeStamp; 727 728 if(!rxTouchIgnoreTags.test(currentElement.tagName)) { 729 e.preventDefault(); 730 } 731 732 switch(e.type) { 733 case EVENT_TOUCHSTART: 734 //The last element we tapped on. 735 if(initialElement) { 736 initialElement.blur(); 737 } 738 739 _instance.stopAnimateTo(); 740 741 initialElement = currentElement; 742 743 initialTouchY = lastTouchY = currentTouchY; 744 initialTouchX = currentTouchX; 745 initialTouchTime = currentTouchTime; 746 747 break; 748 case EVENT_TOUCHMOVE: 749 //Prevent default event on touchIgnore elements in case they don't have focus yet. 750 if(rxTouchIgnoreTags.test(currentElement.tagName) && document.activeElement !== currentElement) { 751 e.preventDefault(); 752 } 753 754 deltaY = currentTouchY - lastTouchY; 755 deltaTime = currentTouchTime - lastTouchTime; 756 757 _instance.setScrollTop(_mobileOffset - deltaY, true); 758 759 lastTouchY = currentTouchY; 760 lastTouchTime = currentTouchTime; 761 break; 762 default: 763 case EVENT_TOUCHCANCEL: 764 case EVENT_TOUCHEND: 765 var distanceY = initialTouchY - currentTouchY; 766 var distanceX = initialTouchX - currentTouchX; 767 var distance2 = distanceX * distanceX + distanceY * distanceY; 768 769 //Check if it was more like a tap (moved less than 7px). 770 if(distance2 < 49) { 771 if(!rxTouchIgnoreTags.test(initialElement.tagName)) { 772 initialElement.focus(); 773 774 //It was a tap, click the element. 775 var clickEvent = document.createEvent('MouseEvents'); 776 clickEvent.initMouseEvent('click', true, true, e.view, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, 0, null); 777 initialElement.dispatchEvent(clickEvent); 778 } 779 780 return; 781 } 782 783 initialElement = undefined; 784 785 var speed = deltaY / deltaTime; 786 787 //Cap speed at 3 pixel/ms. 788 speed = Math.max(Math.min(speed, 3), -3); 789 790 var duration = Math.abs(speed / _mobileDeceleration); 791 var targetOffset = speed * duration + 0.5 * _mobileDeceleration * duration * duration; 792 var targetTop = _instance.getScrollTop() - targetOffset; 793 794 //Relative duration change for when scrolling above bounds. 795 var targetRatio = 0; 796 797 //Change duration proportionally when scrolling would leave bounds. 798 if(targetTop > _maxKeyFrame) { 799 targetRatio = (_maxKeyFrame - targetTop) / targetOffset; 800 801 targetTop = _maxKeyFrame; 802 } else if(targetTop < 0) { 803 targetRatio = -targetTop / targetOffset; 804 805 targetTop = 0; 806 } 807 808 duration = duration * (1 - targetRatio); 809 810 _instance.animateTo((targetTop + 0.5) | 0, {easing: 'outCubic', duration: duration}); 811 break; 812 } 813 }); 814 815 //Just in case there has already been some native scrolling, reset it. 816 window.scrollTo(0, 0); 817 documentElement.style.overflow = body.style.overflow = 'hidden'; 818 }; 819 820 /**
821 * Updates key frames which depend on others / need to be updated on resize. 822 * That is "end" in "absolute" mode and all key frames in "relative" mode. 823 * Also handles constants, because they may change on resize. 824 */ 825 var _updateDependentKeyFrames = function() { 826 var viewportHeight = documentElement.clientHeight; 827 var processedConstants = _processConstants(); 828 var skrollable; 829 var element; 830 var anchorTarget; 831 var keyFrames; 832 var keyFrameIndex; 833 var keyFramesLength; 834 var kf; 835 var skrollableIndex; 836 var skrollablesLength; 837 var offset; 838 var constantValue; 839 840 //First process all relative-mode elements and find the max key frame. 841 skrollableIndex = 0; 842 skrollablesLength = _skrollables.length; 843 844 for(; skrollableIndex < skrollablesLength; skrollableIndex++) { 845 skrollable = _skrollables[skrollableIndex]; 846 element = skrollable.element; 847 anchorTarget = skrollable.anchorTarget; 848 keyFrames = skrollable.keyFrames; 849 850 keyFrameIndex = 0; 851 keyFramesLength = keyFrames.length; 852 853 for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) { 854 kf = keyFrames[keyFrameIndex]; 855 856 offset = kf.offset; 857 constantValue = processedConstants[kf.constant] || 0; 858 859 kf.frame = offset; 860 861 if(kf.isPercentage) { 862 //Convert the offset to percentage of the viewport height. 863 offset = offset * viewportHeight; 864 865 //Absolute + percentage mode. 866 kf.frame = offset; 867 } 868 869 if(kf.mode === 'relative') { 870 _reset(element); 871 872 kf.frame = _instance.relativeToAbsolute(anchorTarget, kf.anchors[0], kf.anchors[1]) - offset; 873 874 _reset(element, true); 875 } 876 877 kf.frame += constantValue; 878 879 //Only search for max key frame when forceHeight is enabled. 880 if(_forceHeight) { 881 //Find the max key frame, but don't use one of the data-end ones for comparison. 882 if(!kf.isEnd && kf.frame > _maxKeyFrame) { 883 _maxKeyFrame = kf.frame; 884 } 885 } 886 } 887 } 888 889 //#133: The document can be larger than the maxKeyFrame we found. 890 _maxKeyFrame = Math.max(_maxKeyFrame, _getDocumentHeight()); 891 892 //Now process all data-end keyframes. 893 skrollableIndex = 0; 894 skrollablesLength = _skrollables.length; 895 896 for(; skrollableIndex < skrollablesLength; skrollableIndex++) { 897 skrollable = _skrollables[skrollableIndex]; 898 keyFrames = skrollable.keyFrames; 899 900 keyFrameIndex = 0; 901 keyFramesLength = keyFrames.length; 902 903 for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) { 904 kf = keyFrames[keyFrameIndex]; 905 906 constantValue = processedConstants[kf.constant] || 0; 907 908 if(kf.isEnd) { 909 kf.frame = _maxKeyFrame - kf.offset + constantValue; 910 } 911 } 912 913 skrollable.keyFrames.sort(_keyFrameComparator); 914 } 915 }; 916 917 /** 918 * Calculates and sets the style properties for the element at the given frame. 919 * @param fakeFrame The frame to render at when smooth scrolling is enabled. 920 * @param actualFrame The actual frame we are at. 921 */ 922 var _calcSteps = function(fakeFrame, actualFrame) { 923 //Iterate over all skrollables. 924 var skrollableIndex = 0; 925 var skrollablesLength = _skrollables.length; 926 927 for(; skrollableIndex < skrollablesLength; skrollableIndex++) { 928 var skrollable = _skrollables[skrollableIndex]; 929 var element = skrollable.element; 930 var frame = skrollable.smoothScrolling ? fakeFrame : actualFrame; 931 var frames = skrollable.keyFrames; 932 var framesLength = frames.length; 933 var firstFrame = frames[0]; 934 var lastFrame = frames[frames.length - 1]; 935 var beforeFirst = frame < firstFrame.frame; 936 var afterLast = frame > lastFrame.frame; 937 var firstOrLastFrame = beforeFirst ? firstFrame : lastFrame; 938 var emitEvents = skrollable.emitEvents; 939 var lastFrameIndex = skrollable.lastFrameIndex; 940 var key; 941 var value; 942 943 //If we are before/after the first/last frame, set the styles according to the given edge strategy. 944 if(beforeFirst || afterLast) { 945 //Check if we already handled this edge case last time. 946 //Note: using setScrollTop it's possible that we jumped from one edge to the other. 947 if(beforeFirst && skrollable.edge === -1 || afterLast && skrollable.edge === 1) { 948 continue; 949 } 950 951 //Add the skrollr-before or -after class. 952 if(beforeFirst) {
953 _updateClass(element, [SKROLLABLE_BEFORE_CLASS], [SKROLLABLE_AFTER_CLASS, SKROLLABLE_BETWEEN_CLASS]); 954 955 //This handles the special case where we exit the first keyframe. 956 if(emitEvents && lastFrameIndex > -1) { 957 _emitEvent(element, firstFrame.eventType, _direction); 958 skrollable.lastFrameIndex = -1; 959 } 960 } else { 961 _updateClass(element, [SKROLLABLE_AFTER_CLASS], [SKROLLABLE_BEFORE_CLASS, SKROLLABLE_BETWEEN_CLASS]); 962 963 //This handles the special case where we exit the last keyframe. 964 if(emitEvents && lastFrameIndex < framesLength) { 965 _emitEvent(element, lastFrame.eventType, _direction); 966 skrollable.lastFrameIndex = framesLength; 967 } 968 } 969 970 //Remember that we handled the edge case (before/after the first/last keyframe). 971 skrollable.edge = beforeFirst ? -1 : 1; 972 973 switch(skrollable.edgeStrategy) { 974 case 'reset': 975 _reset(element); 976 continue; 977 case 'ease': 978 //Handle this case like it would be exactly at first/last keyframe and just pass it on. 979 frame = firstOrLastFrame.frame; 980 break; 981 default: 982 case 'set': 983 var props = firstOrLastFrame.props; 984 985 for(key in props) { 986 if(hasProp.call(props, key)) { 987 value = _interpolateString(props[key].value); 988 989 //Set style or attribute. 990 if(key.indexOf('@') === 0) { 991 element.setAttribute(key.substr(1), value); 992 } else { 993 skrollr.setStyle(element, key, value); 994 } 995 } 996 } 997 998 continue; 999 } 1000 } else { 1001 //Did we handle an edge last time? 1002 if(skrollable.edge !== 0) { 1003 _updateClass(element, [SKROLLABLE_CLASS, SKROLLABLE_BETWEEN_CLASS], [SKROLLABLE_BEFORE_CLASS, SKROLLABLE_AFTER_CLASS]); 1004 skrollable.edge = 0; 1005 } 1006 } 1007 1008 //Find out between which two key frames we are right now. 1009 var keyFrameIndex = 0; 1010 1011 for(; keyFrameIndex < framesLength - 1; keyFrameIndex++) { 1012 if(frame >= frames[keyFrameIndex].frame && frame <= frames[keyFrameIndex + 1].frame) { 1013 var left = frames[keyFrameIndex]; 1014 var right = frames[keyFrameIndex + 1]; 1015 1016 for(key in left.props) { 1017 if(hasProp.call(left.props, key)) { 1018 var progress = (frame - left.frame) / (right.frame - left.frame); 1019 1020 //Transform the current progress using the given easing function. 1021 progress = left.props[key].easing(progress); 1022 1023 //Interpolate between the two values 1024 value = _calcInterpolation(left.props[key].value, right.props[key].value, progress); 1025 1026 value = _interpolateString(value); 1027 1028 //Set style or attribute. 1029 if(key.indexOf('@') === 0) { 1030 element.setAttribute(key.substr(1), value); 1031 } else { 1032 skrollr.setStyle(element, key, value); 1033 } 1034 } 1035 } 1036 1037 //Are events enabled on this element? 1038 //This code handles the usual cases of scrolling through different keyframes. 1039 //The special cases of before first and after last keyframe are handled above. 1040 if(emitEvents) { 1041 //Did we pass a new keyframe? 1042 if(lastFrameIndex !== keyFrameIndex) { 1043 if(_direction === 'down') { 1044 _emitEvent(element, left.eventType, _direction); 1045 } else { 1046 _emitEvent(element, right.eventType, _direction); 1047 } 1048 1049 skrollable.lastFrameIndex = keyFrameIndex; 1050 } 1051 } 1052 1053 break; 1054 } 1055 } 1056 } 1057 }; 1058 1059 /** 1060 * Renders all elements. 1061 */ 1062 var _render = function() { 1063 if(_requestReflow) { 1064 _requestReflow = false; 1065 _reflow(); 1066 } 1067 1068 //We may render something else than the actual scrollbar position. 1069 var renderTop = _instance.getScrollTop(); 1070 1071 //If there's an animation, which ends in current render call, call the callback after rendering. 1072 var afterAnimationCallback; 1073 var now = _now(); 1074 var progress; 1075 1076 //Before actually rendering handle the scroll animation, if any. 1077 if(_scrollAnimation) { 1078 //It's over 1079 if(now >= _scrollAnimation.endTime) { 1080 renderTop = _scrollAnimation.targetTop; 1081 afterAnimationCallback = _scrollAnimation.done; 1082 _scrollAnimation = undefined; 1083 } else { 1084 //Map the current progress to the new progress using given easing function. 1085 progress = _scrollAnimation.easing((now - _scrollAnimation.startTime) / _scrollAnimation.duration); 1086 1087 renderTop = (_scrollAnimation.startTop + progress * _scrollAnimation.topDiff) | 0; 1088 } 1089 1090 _instance.setScrollTop(renderTop, true); 1091 } 1092 //Smooth scrolling only if there's no animation running and if we're not forcing the rendering. 1093 else if(!_forceRender) { 1094 var smoothScrollingDiff = _smoothScrolling.targetTop - renderTop; 1095 1096 //The user scrolled, start new smooth scrolling. 1097 if(smoothScrollingDiff) { 1098 _smoothScrolling = { 1099 startTop: _lastTop, 1100 topDiff: renderTop - _lastTop, 1101 targetTop: renderTop, 1102 startTime: _lastRenderCall, 1103 endTime: _lastRenderCall + _smoothScrollingDuration 1104 }; 1105 } 1106 1107 //Interpolate the internal scroll position (not the actual scrollbar). 1108 if(now <= _smoothScrolling.endTime) { 1109 //Map the current progress to the new progress using easing function. 1110 progress = easings.sqrt((now - _smoothScrolling.startTime) / _smoothScrollingDuration); 1111 1112 renderTop = (_smoothScrolling.startTop + progress * _smoothScrolling.to
1112pDiff) | 0; 1113 } 1114 } 1115 1116 //That's were we actually "scroll" on mobile. 1117 if(_isMobile && _skrollrBody) { 1118 //Set the transform ("scroll it"). 1119 skrollr.setStyle(_skrollrBody, 'transform', 'translate(0, ' + -(_mobileOffset) + 'px) ' + _translateZ); 1120 } 1121 1122 //Did the scroll position even change? 1123 if(_forceRender || _lastTop !== renderTop) { 1124 //Remember in which direction are we scrolling? 1125 _direction = (renderTop > _lastTop) ? 'down' : (renderTop < _lastTop ? 'up' : _direction); 1126 1127 _forceRender = false; 1128 1129 var listenerParams = { 1130 curTop: renderTop, 1131 lastTop: _lastTop, 1132 maxTop: _maxKeyFrame, 1133 direction: _direction 1134 }; 1135 1136 //Tell the listener we are about to render. 1137 var continueRendering = _listeners.beforerender && _listeners.beforerender.call(_instance, listenerParams); 1138 1139 //The beforerender listener function is able the cancel rendering. 1140 if(continueRendering !== false) { 1141 //Now actually interpolate all the styles. 1142 _calcSteps(renderTop, _instance.getScrollTop()); 1143 1144 //Remember when we last rendered. 1145 _lastTop = renderTop; 1146 1147 if(_listeners.render) { 1148 _listeners.render.call(_instance, listenerParams); 1149 } 1150 } 1151 1152 if(afterAnimationCallback) { 1153 afterAnimationCallback.call(_instance, false); 1154 } 1155 } 1156 1157 _lastRenderCall = now; 1158 }; 1159 1160 /** 1161 * Parses the properties for each key frame of the given skrollable. 1162 */ 1163 var _parseProps = function(skrollable) { 1164 //Iterate over all key frames 1165 var keyFrameIndex = 0; 1166 var keyFramesLength = skrollable.keyFrames.length; 1167 1168 for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) { 1169 var frame = skrollable.keyFrames[keyFrameIndex]; 1170 var easing; 1171 var value; 1172 var prop; 1173 var props = {}; 1174 1175 var match; 1176 1177 while((match = rxPropValue.exec(frame.props)) !== null) { 1178 prop = match[1]; 1179 value = match[2]; 1180 1181 easing = prop.match(rxPropEasing); 1182 1183 //Is there an easing specified for this prop? 1184 if(easing !== null) { 1185 prop = easing[1]; 1186 easing = easing[2]; 1187 } else { 1188 easing = DEFAULT_EASING; 1189 } 1190 1191 //Exclamation point at first position forces the value to be taken literal. 1192 value = value.indexOf('!') ? _parseProp(value) : [value.slice(1)]; 1193 1194 //Save the prop for this key frame with his value and easing function 1195 props[prop] = { 1196 value: value, 1197 easing: easings[easing] 1198 }; 1199 } 1200 1201 frame.props = props; 1202 } 1203 }; 1204 1205 /** 1206 * Parses a value extracting numeric values and generating a format string 1207 * for later interpolation of the new values in old string. 1208 * 1209 * @param val The CSS value to be parsed. 1210 * @return Something like ["rgba(?%,?%, ?%,?)", 100, 50, 0, .7] 1211 * where the first element is the format string later used 1212 * and all following elements are the numeric value. 1213 */ 1214 var _parseProp = function(val) { 1215 var numbers = []; 1216 1217 //One special case, where floats don't work. 1218 //We replace all occurences of rgba colors 1219 //which don't use percentage notation with the percentage notation. 1220 rxRGBAIntegerColor.lastIndex = 0; 1221 val = val.replace(rxRGBAIntegerColor, function(rgba) { 1222 return rgba.replace(rxNumericValue, function(n) { 1223 return n / 255 * 100 + '%'; 1224 }); 1225 }); 1226 1227 //Handle prefixing of "gradient" values. 1228 //For now only the prefixed value will be set. Unprefixed isn't supported anyway. 1229 if(theDashedCSSPrefix) { 1230 rxGradient.lastIndex = 0; 1231 val = val.replace(rxGradient, function(s) { 1232 return theDashedCSSPrefix + s; 1233 }); 1234 } 1235 1236 //Now parse ANY number inside this string and create a format string. 1237 val = val.replace(rxNumericValue, function(n) { 1238 numbers.push(+n); 1239 return '{?}'; 1240 }); 1241 1242 //Add the formatstring as first value. 1243 numbers.unshift(val); 1244 1245 return numbers; 1246 }; 1247 1248 /** 1249 * Fills the key frames with missing left and right hand properties. 1250 * If key frame 1 has property X and key frame 2 is missing X, 1251 * but key frame 3 has X again, then we need to assign X to key frame 2 too. 1252 * 1253 * @param sk A skrollable. 1254 */ 1255 var _fillProps = function(sk) { 1256 //Will collect the properties key frame by key frame 1257 var propList = {}; 1258 var keyFrameIndex; 1259 var keyFramesLength; 1260 1261 //Iterate over all key frames from left to right 1262 keyFrameIndex = 0; 1263 keyFramesLength = sk.keyFrames.length; 1264 1265 for(; keyFrameIndex < keyFramesLength; keyFrameIndex++) { 1266 _fillPropForFrame(sk.keyFrames[keyFrameIndex], propList); 1267 } 1268 1269 //Now do the same from right to fill the last gaps 1270 1271 propList = {}; 1272 1273 //Iterate over all key frames from right to left 1274 keyFrameIndex = sk.keyFrames.length - 1; 1275 1276 for(; keyFrameIndex >= 0; keyFrameIndex--) { 1277 _fillPropForFrame(sk.keyFrames[keyFrameIndex], propList); 1278 } 1279 }; 1280 1281 var _fillPropForFrame = function(frame, propList) { 1282 var key; 1283 1284 //For each key frame iterate over all right hand properties and assign them, 1285 //but only if the current key frame doesn't have the property by itself 1286 for(key in propList) { 1287 //The current frame misses this property, so assign it. 1288 if(!hasProp.call(frame.props, key)) { 1289 frame.props[key] = propList[key]; 1290 } 1291 } 1292 1293 //Iterate over all props of the current frame and collect them 1294 for(key in frame.props) { 1295 propList[key] = frame.props[key]; 1296 } 1297 }; 1298 1299 /** 1300 * Calculates the new values for two given values array. 1301 */ 1302 var _calcInterpolation = function(val1, val2, progress) { 1303 var valueIndex; 1304 var val1Length = val1.length; 1305 1306 //They both need to have the same length 1307 if(val1Length !== val2.length) { 1308 throw 'Can\'t interpolate between "' + val1[0] + '" and "' + val2[0] + '"'; 1309 } 1310
1311 //Add the format string as first element. 1312 var interpolated = [val1[0]]; 1313 1314 valueIndex = 1; 1315 1316 for(; valueIndex < val1Length; valueIndex++) { 1317 //That's the line where the two numbers are actually interpolated. 1318 interpolated[valueIndex] = val1[valueIndex] + ((val2[valueIndex] - val1[valueIndex]) * progress); 1319 } 1320 1321 return interpolated; 1322 }; 1323 1324 /** 1325 * Interpolates the numeric values into the format string. 1326 */ 1327 var _interpolateString = function(val) { 1328 var valueIndex = 1; 1329 1330 rxInterpolateString.lastIndex = 0; 1331 1332 return val[0].replace(rxInterpolateString, function() { 1333 return val[valueIndex++]; 1334 }); 1335 }; 1336 1337 /** 1338 * Resets the class and style attribute to what it was before skrollr manipulated the element. 1339 * Also remembers the values it had before reseting, in order to undo the reset. 1340 */ 1341 var _reset = function(elements, undo) { 1342 //We accept a single element or an array of elements. 1343 elements = [].concat(elements); 1344 1345 var skrollable; 1346 var element; 1347 var elementsIndex = 0; 1348 var elementsLength = elements.length; 1349 1350 for(; elementsIndex < elementsLength; elementsIndex++) { 1351 element = elements[elementsIndex]; 1352 skrollable = _skrollables[element[SKROLLABLE_ID_DOM_PROPERTY]]; 1353 1354 //Couldn't find the skrollable for this DOM element. 1355 if(!skrollable) { 1356 continue; 1357 } 1358 1359 if(undo) { 1360 //Reset class and style to the "dirty" (set by skrollr) values. 1361 element.style.cssText = skrollable.dirtyStyleAttr; 1362 _updateClass(element, skrollable.dirtyClassAttr); 1363 } else { 1364 //Remember the "dirty" (set by skrollr) class and style. 1365 skrollable.dirtyStyleAttr = element.style.cssText; 1366 skrollable.dirtyClassAttr = _getClass(element); 1367 1368 //Reset class and style to what it originally was. 1369 element.style.cssText = skrollable.styleAttr; 1370 _updateClass(element, skrollable.classAttr); 1371 } 1372 } 1373 }; 1374 1375 /** 1376 * Detects support for 3d transforms by applying it to the skrollr-body. 1377 */ 1378 var _detect3DTransforms = function() { 1379 _translateZ = 'translateZ(0)'; 1380 skrollr.setStyle(_skrollrBody, 'transform', _translateZ); 1381 1382 var computedStyle = getStyle(_skrollrBody); 1383 var computedTransform = computedStyle.getPropertyValue('transform'); 1384 var computedTransformWithPrefix = computedStyle.getPropertyValue(theDashedCSSPrefix + 'transform'); 1385 var has3D = (computedTransform && computedTransform !== 'none') || (computedTransformWithPrefix && computedTransformWithPrefix !== 'none'); 1386 1387 if(!has3D) { 1388 _translateZ = ''; 1389 } 1390 }; 1391 1392 /** 1393 * Set the CSS property on the given element. Sets prefixed properties as well. 1394 */ 1395 skrollr.setStyle = function(el, prop, val) { 1396 var style = el.style; 1397 1398 //Camel case. 1399 prop = prop.replace(rxCamelCase, rxCamelCaseFn).replace('-', ''); 1400 1401 //Make sure z-index gets a <integer>. 1402 //This is the only <integer> case we need to handle. 1403 if(prop === 'zIndex') { 1404 if(isNaN(val)) { 1405 //If it's not a number, don't touch it. 1406 //It could for example be "auto" (#351). 1407 style[prop] = val; 1408 } else { 1409 //Floor the number. 1410 style[prop] = '' + (val | 0); 1411 } 1412 } 1413 //#64: "float" can't be set across browsers. Needs to use "cssFloat" for all except IE. 1414 else if(prop === 'float') { 1415 style.styleFloat = style.cssFloat = val; 1416 } 1417 else { 1418 //Need try-catch for old IE. 1419 try { 1420 //Set prefixed property if there's a prefix. 1421 if(theCSSPrefix) { 1422 style[theCSSPrefix + prop.slice(0,1).toUpperCase() + prop.slice(1)] = val; 1423 } 1424 1425 //Set unprefixed. 1426 style[prop] = val; 1427 } catch(ignore) {} 1428 } 1429 }; 1430 1431 /** 1432 * Cross browser event handling. 1433 */ 1434 var _addEvent = skrollr.addEvent = function(element, names, callback) { 1435 var intermediate = function(e) { 1436 //Normalize IE event stuff. 1437 e = e || window.event; 1438 1439 if(!e.target) { 1440 e.target = e.srcElement; 1441 } 1442 1443 if(!e.preventDefault) { 1444 e.preventDefault = function() { 1445 e.returnValue = false; 1446 e.defaultPrevented = true; 1447 }; 1448 } 1449 1450 return callback.call(this, e); 1451 }; 1452 1453 names = names.split(' '); 1454 1455 var name; 1456 var nameCounter = 0; 1457 var namesLength = names.length; 1458 1459 for(; nameCounter < namesLength; nameCounter++) { 1460 name = names[nameCounter]; 1461 1462 if(element.addEventListener) { 1463 element.addEventListener(name, callback, false); 1464 } else { 1465 element.attachEvent('on' + name, intermediate); 1466 } 1467 1468 //Remember the events to be able to flush them later. 1469 _registeredEvents.push({ 1470 element: element, 1471 name: name, 1472 listener: callback 1473 }); 1474 } 1475 }; 1476 1477 var _removeEvent = skrollr.removeEvent = function(element, names, callback) { 1478 names = names.split(' '); 1479 1480 var nameCounter = 0; 1481 var namesLength = names.length; 1482 1483 for(; nameCounter < namesLength; nameCounter++) { 1484 if(element.removeEventListener) { 1485 element.removeEventListener(names[nameCounter], callback, false); 1486 } else { 1487 element.detachEvent('on' + names[nameCounter], callback); 1488 } 1489 } 1490 }; 1491 1492 var _removeAllEvents = function() { 1493 var eventData; 1494 var eventCounter = 0; 1495 var eventsLength = _registeredEvents.length; 1496 1497 for(; eventCounter < eventsLength; eventCounter++) { 1498 eventData = _registeredEvents[eventCounter]; 1499 1500 _removeEvent(eventData.element, eventData.name, eventData.listener); 1501 } 1502 1503 _registeredEvents = []; 1504 }; 1505 1506 var _emitEvent = function(element, name, direction) { 1507 if(_listeners.keyframe) { 1508 _listeners.keyframe.call(_instance, element, name, direction); 1509 } 1510 }; 1511 1512 var _reflow = function() { 1513 var pos = _instance.getScrollTop(); 1514 1515 //Will be recalculated by _updateDependentKeyFrames. 1516 _maxKeyFrame = 0; 1517 1518 if(_forceHeight && !_isMobile) { 1519 //un-"force" the height to not mess with the calculations in _updateDependentKeyFrames (#216). 1520 body.style.height = ''; 1521 } 1522 1523 _updateDependentKeyFrames(); 1524 1525 if(_forceHeight && !_isMobile) { 1526 //"force" the height. 1527 body.style.height = (_maxKeyFrame + documentElement.clientHeight) + 'px'; 1528 } 1529 1530 //The scroll offset may now be larger than needed (on desktop the browser/os prevents scrolling farther than the bottom). 1531 if(_isMobile) { 1532 _instance.setScrollTop(Math.min(_instance.getScrollTop(), _maxKeyFrame)); 1533 } else { 1534 //Remember and reset the scroll pos (#217). 1535 _instance.setScrollTop(pos, true); 1536 } 1537 1538 _forceRender = true; 1539 }; 1540 1541 /* 1542 * Returns a copy of the constants object where all functions and strings have been evaluated. 1543 */ 1544 var _processConstants = function() {
1545 var viewportHeight = documentElement.clientHeight; 1546 var copy = {}; 1547 var prop; 1548 var value; 1549 1550 for(prop in _constants) { 1551 value = _constants[prop]; 1552 1553 if(typeof value === 'function') { 1554 value = value.call(_instance); 1555 } 1556 //Percentage offset. 1557 else if((/p$/).test(value)) { 1558 value = (value.slice(0, -1) / 100) * viewportHeight; 1559 } 1560 1561 copy[prop] = value; 1562 } 1563 1564 return copy; 1565 }; 1566 1567 /* 1568 * Returns the height of the document. 1569 */ 1570 var _getDocumentHeight = function() { 1571 var skrollrBodyHeight = 0; 1572 var bodyHeight; 1573 1574 if(_skrollrBody) { 1575 skrollrBodyHeight = Math.max(_skrollrBody.offsetHeight, _skrollrBody.scrollHeight); 1576 } 1577 1578 bodyHeight = Math.max(skrollrBodyHeight, body.scrollHeight, body.offsetHeight, documentElement.scrollHeight, documentElement.offsetHeight, documentElement.clientHeight); 1579 1580 return bodyHeight - documentElement.clientHeight; 1581 }; 1582 1583 /** 1584 * Returns a string of space separated classnames for the current element. 1585 * Works with SVG as well. 1586 */ 1587 var _getClass = function(element) { 1588 var prop = 'className'; 1589 1590 //SVG support by using className.baseVal instead of just className. 1591 if(window.SVGElement && element instanceof window.SVGElement) { 1592 element = element[prop]; 1593 prop = 'baseVal'; 1594 } 1595 1596 return element[prop]; 1597 }; 1598 1599 /** 1600 * Adds and removes a CSS classes. 1601 * Works with SVG as well.
1602 * add and remove are arrays of strings, 1603 * or if remove is ommited add is a string and overwrites all classes. 1604 */ 1605 var _updateClass = function(element, add, remove) { 1606 var prop = 'className'; 1607 1608 //SVG support by using className.baseVal instead of just className. 1609 if(window.SVGElement && element instanceof window.SVGElement) { 1610 element = element[prop]; 1611 prop = 'baseVal'; 1612 } 1613 1614 //When remove is ommited, we want to overwrite/set the classes. 1615 if(remove === undefined) { 1616 element[prop] = add; 1617 return; 1618 } 1619 1620 //Cache current classes. We will work on a string before passing back to DOM. 1621 var val = element[prop]; 1622 1623 //All classes to be removed. 1624 var classRemoveIndex = 0; 1625 var removeLength = remove.length; 1626 1627 for(; classRemoveIndex < removeLength; classRemoveIndex++) { 1628 val = _untrim(val).replace(_untrim(remove[classRemoveIndex]), ' '); 1629 } 1630 1631 val = _trim(val); 1632 1633 //All classes to be added. 1634 var classAddIndex = 0; 1635 var addLength = add.length; 1636 1637 for(; classAddIndex < addLength; classAddIndex++) { 1638 //Only add if el not already has class. 1639 if(_untrim(val).indexOf(_untrim(add[classAddIndex])) === -1) { 1640 val += ' ' + add[classAddIndex]; 1641 } 1642 } 1643 1644 element[prop] = _trim(val); 1645 }; 1646 1647 var _trim = function(a) { 1648 return a.replace(rxTrim, ''); 1649 }; 1650 1651 /** 1652 * Adds a space before and after the string. 1653 */ 1654 var _untrim = function(a) { 1655 return ' ' + a + ' '; 1656 }; 1657 1658 var _now = Date.now || function() { 1659 return +new Date(); 1660 }; 1661 1662 var _keyFrameComparator = function(a, b) { 1663 return a.frame - b.frame; 1664 }; 1665 1666 /* 1667 * Private variables. 1668 */ 1669 1670 //Singleton 1671 var _instance; 1672 1673 /* 1674 A list of all elements which should be animated associated with their the metadata. 1675 Exmaple skrollable with two key frames animating from 100px width to 20px: 1676 1677 skrollable = { 1678 element: <the DOM element>, 1679 styleAttr: <style attribute of the element before skrollr>, 1680 classAttr: <class attribute of the element before skrollr>, 1681 keyFrames: [ 1682 { 1683 frame: 100, 1684 props: { 1685 width: { 1686 value: ['{?}px', 100], 1687 easing: <reference to easing function> 1688 } 1689 }, 1690 mode: "absolute" 1691 }, 1692 { 1693 frame: 200, 1694 props: { 1695 width: { 1696 value: ['{?}px', 20], 1697 easing: <reference to easing function> 1698 } 1699 }, 1700 mode: "absolute" 1701 } 1702 ] 1703 }; 1704 */ 1705 var _skrollables; 1706 1707 var _skrollrBody; 1708 1709 var _listeners; 1710 var _forceHeight; 1711 var _maxKeyFrame = 0; 1712 1713 var _scale = 1; 1714 var _constants; 1715 1716 var _mobileDeceleration; 1717 1718 //Current direction (up/down). 1719 var _direction = 'down'; 1720 1721 //The last top offset value. Needed to determine direction. 1722 var _lastTop = -1; 1723 1724 //The last time we called the render method (doesn't mean we rendered!). 1725 var _lastRenderCall = _now(); 1726 1727 //For detecting if it actually resized (#271). 1728 var _lastViewportWidth = 0; 1729 var _lastViewportHeight = 0; 1730 1731 var _requestReflow = false; 1732 1733 //Will contain data about a running scrollbar animation, if any. 1734 var _scrollAnimation; 1735 1736 var _smoothScrollingEnabled; 1737 1738 var _smoothScrollingDuration; 1739 1740 //Will contain settins for smooth scrolling if enabled. 1741 var _smoothScrolling; 1742 1743 //Can be set by any operation/event to force rendering even if the scrollbar didn't move. 1744 var _forceRender; 1745 1746 //Each skrollable gets an unique ID incremented for each skrollable. 1747 //The ID is the index in the _skrollables array. 1748 var _skrollableIdCounter = 0; 1749 1750 var _edgeStrategy; 1751 1752 1753 //Mobile specific vars. Will be stripped by UglifyJS when not in use. 1754 var _isMobile = false; 1755 1756 //The virtual scroll offset when using mobile scrolling. 1757 var _mobileOffset = 0; 1758 1759 //If the browser supports 3d transforms, this will be filled with 'translateZ(0)' (empty string otherwise). 1760 var _translateZ; 1761 1762 //Will contain data about registered events by skrollr. 1763 var _registeredEvents = []; 1764 1765 //Animation frame id returned by RequestAnimationFrame (or timeout when RAF is not supported). 1766 var _animFrame; 1767 1768 //Expose skrollr as either a global variable or a require.js module. 1769 if(typeof define === 'function' && define.amd) { 1770 define([], function () { 1771 return skrollr; 1772 }); 1773 } else if (typeof module !== 'undefined' && module.exports) { 1774 module.exports = skrollr; 1775 } else { 1776 window.skrollr = skrollr; 1777 } 1778 1779}(window, document));
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.