# all files / parallax/ source.js

84.62% Statements 22/26
83.33% Branches 5/6
66.67% Functions 4/6
81.82% Lines 18/22

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    521×
    1×

    6×

    6×

    6×

    6×
    1×
    5×
    1×

    4×

    1×
    1×
    1×

    1×

    1×

    1×

    1×

    1×

     import 'core-js/modules/es6.object.assign';
    import 'core-js/modules/es6.array.from';

    export default class Parallax {
      constructor(selector, options) {
        this.lastPosition = -1;

        // Establish default settings
        this.settings = Object.assign({
          speed: 0.2,
        }, options);

        if (typeof selector === 'string') {
          this.elems = Array.from(document.querySelectorAll(selector));
        } else if (Array.isArray(selector)) {
          this.elems = selector;
        } else {
          this.elems = [selector];
        }
      }

      updatePosition() {
        this.elems.forEach((elem) => {
          const offset = elem.getBoundingClientRect().top + this.lastPosition;
          const yPosition = Math.round((offset - this.lastPosition) * this.settings.speed);

          // Apply the y-axis transform
          elem.style.transform = `translate3d(0, ${yPosition * -1}px, 0)`; // eslint-disable-line
        });
      }

      animate() {
        // If the offset position hasn't changed, skip this frame
        if (Ithis.lastPosition === window.pageYOffset) {
          window.requestAnimationFrame(() => {
            this.animate();
          });

          return false;
        }

        // Save the new offset position
        this.lastPosition = window.pageYOffset;

        this.updatePosition();

        return window.requestAnimationFrame(() => {
          this.animate();
        });
      }
    }