Skip to content

Commit

Permalink
Used getBoundingClientRect function instead of getOffsetSum
Browse files Browse the repository at this point in the history
  • Loading branch information
hsnaydd committed Sep 28, 2017
1 parent 0d2098f commit 36fb964
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 29 deletions.
35 changes: 6 additions & 29 deletions src/moveTo.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,6 @@ const MoveTo = (() => {
return -c * (t * t * t * t - 1) + b;
}

/**
* Returns html element's top and left offset
* @param {HTMLElement} elem - Element
* @return {object} Element top and left offset
*/
function getOffsetSum(elem) {
if(typeof elem.getBoundingClientRect == 'function') {
return elem.getBoundingClientRect();
} else {
let top = 0;
let left = 0;
while (elem) {
top += elem.offsetTop;
left += elem.offsetLeft;
elem = elem.offsetParent;
}
return {
top, left,
};
}
}

/**
* Merge two object
*
Expand Down Expand Up @@ -132,12 +110,11 @@ const MoveTo = (() => {

options = mergeObject(this.options, options);

let to = typeof target === 'number' ? target : getOffsetSum(target).top;
let distance = typeof target === 'number' ? target : target.getBoundingClientRect().top;
const from = window.pageYOffset;
to -= options.tolerance;
const change = to - from;
let startTime = null;
let lastPageYOffset;
distance -= options.tolerance;

// rAF loop
const loop = (currentTime) => {
Expand All @@ -154,24 +131,24 @@ const MoveTo = (() => {

if (lastPageYOffset) {
if (
(change > 0 && lastPageYOffset > currentPageYOffset) ||
(change < 0 && lastPageYOffset < currentPageYOffset)
(distance > 0 && lastPageYOffset > currentPageYOffset) ||
(distance < 0 && lastPageYOffset < currentPageYOffset)
) {
return options.callback(target);
}
}
lastPageYOffset = currentPageYOffset;

const val = this.easeFunctions[options.easing](
timeElapsed, from, change, options.duration
timeElapsed, from, distance, options.duration
);

window.scroll(0, val);

if (timeElapsed < options.duration) {
window.requestAnimationFrame(loop);
} else {
window.scroll(0, to);
window.scroll(0, distance + from);
options.callback(target);
}
};
Expand Down
3 changes: 3 additions & 0 deletions tests/moveTo-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ function createMockDomElement(options) {
},
removeEventListener: function(event, cb) {
delete this._listeners[event];
},
getBoundingClientRect: function() {
return {top: options.offsetTop || 0};
}
};
}
Expand Down

0 comments on commit 36fb964

Please sign in to comment.