Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made options for scrollLeft and fix callback bug #11

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ button.addEventListener('click', function () {
document.body, // element to scroll with (most of times you want to scroll with whole <body>)
0, // target scrollY (0 means top of the page)
10000, // duration in ms
true, // horizontal scrolling?
function() { // callback function that runs after the animation (optional)
console.log('done!')
}
Expand Down
18 changes: 11 additions & 7 deletions animatedScrollTo.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,39 @@
return -c/2 * (t*(t-2) - 1) + b;
};

var animatedScrollTo = function (element, to, duration, callback) {
var start = element.scrollTop,
var animatedScrollTo = function (element, to, duration, scrollLeft, callback) {

var direction = 'scrollTop'
if (scrollLeft) direction = 'scrollLeft'

var start = element[direction],
change = to - start,
animationStart = +new Date();
var animating = true;
var lastpos = null;

var animateScroll = function() {
if (!animating) {
if (callback) { callback(); }
return;
}
requestAnimFrame(animateScroll);
var now = +new Date();
var val = Math.floor(easeInOutQuad(now - animationStart, start, change, duration));
if (lastpos) {
if (lastpos === element.scrollTop) {
if (lastpos === element[direction]) {
lastpos = val;
element.scrollTop = val;
element[direction] = val;
} else {
animating = false;
}
} else {
lastpos = val;
element.scrollTop = val;
element[direction] = val;
}
if (now > animationStart + duration) {
element.scrollTop = to;
element[direction] = to;
animating = false;
if (callback) { callback(); }
}
};
requestAnimFrame(animateScroll);
Expand Down