UNPKG

scrolltojstesting

Version:

Module for scroll-to functionality

151 lines (124 loc) 3.22 kB
import $ from 'jquery'; export default class ScrollTo { /** * Create an instance of ScrollTo * @param target {string} [target selector] * @param setup {object} [alignments: bottom | center | need more? add to _defaults] */ constructor(target = '', setup = {}) { this.$target = $(target); if (!this.$target.length) { return false; } const _defaults = { align: 'bottom', scrollTarget: 'html, body', offset: 0, duration: 500 }; this.setup = Object.assign({}, _defaults, setup); this.customScrollTarget = this.setup.scrollTarget !== 'html, body'; this.duration = this.setup.duration; this.alignment = this.setup.align; this.offset = this.setup.offset; this.$scrollTarget = $(this.setup.scrollTarget); this.$window = $(window); this.overflowHeight = this.getOverflow(); this.bottomEdgeIsVisible = this.overflowHeight <= 0; } // get headerHeight of fixed header get headerHeight() { const pageHeader = $('header:first-of-type'); let fixedHeaderHeight = 0; if (pageHeader.css('position') == 'fixed') { fixedHeaderHeight = pageHeader.outerHeight(); } console.log('getHederHeight'); return fixedHeaderHeight; } get pageTop() { let top; if (this.customScrollTarget) { top = this.$scrollTarget.scrollTop(); } else { top = this.$window.scrollTop() + this.headerHeight; } return top + this.setup.offset; } get toggleTop() { let top; if (this.customScrollTarget) { top = this.$target.position().top; } else { top = this.$target.offset().top; } return top; } getBottom = () => { const pageBottom = this.pageTop + this.$window.height(); const toggleBottom = this.toggleTop + this.$target.height(); return toggleBottom - pageBottom; }; getTop = () => { return this.toggleTop - this.pageTop; }; getCenter = () => { const pageCenter = this.pageTop + this.$window.height() / 2; const toggleCenter = this.toggleTop + this.$target.height() / 2; return toggleCenter - pageCenter; }; /** * Returns ScrollToOffset for desired position * @returns {number} */ getOverflow = () => { let height = false; if (this.alignment === 'bottom') { height = this.getBottom(); } if (this.alignment === 'center') { height = this.getCenter(); } if (this.alignment === 'top') { height = this.getTop(); } if (height === false) { height = 0; } return height; }; /** * Returns the offset to scroll to. * @returns {number} */ getOffset = () => { let offset; if (this.customScrollTarget) { offset = this.overflowHeight; } else { offset = $(document).scrollTop() + this.overflowHeight; } return offset; }; /** * Executes scroll animation to calculated offset. * @memberOf ScrollTo */ go = cb => { this.$scrollTarget .animate( { scrollTop: this.getOffset() }, { duration: this.duration } ) .promise() .done(() => { if (cb) { cb(); } }); }; }