Skip to content

Instantly share code, notes, and snippets.

@syntagmatic
Last active September 26, 2016 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syntagmatic/2034946 to your computer and use it in GitHub Desktop.
Save syntagmatic/2034946 to your computer and use it in GitHub Desktop.
Scroller - Add a button to scroll smoothly down a page
// run in a javascript console to add an auto-scroller to the page
var scroller = (function() {
var button = document.createElement('button'),
scroller = {},
scrollerY = 0,
going = false,
last = 0,
requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
scroller.speed = 10;
function step(timestamp) {
var progress = timestamp - last;
// adjust if user scrolls
if (Math.abs(window.scrollY - scrollerY) > 4) scrollerY = window.scrollY;
// check if scrolling 1px
if (progress > (1000/scroller.speed)) {
last = timestamp;
window.scrollTo(0,scrollerY++)
}
// reset at bottom of page
if (window.scrollY < scrollerY - 4) {
window.scrollTo(0,scrollerY=0)
}
// continue
if (going) {
requestAnimationFrame(step);
}
}
// start scrolling
scroller.go = function() {
going = true;
scrollerY = window.scrollY;
requestAnimationFrame(step);
button.onclick = scroller.pause;
button.innerHTML = "pause";
style(button, {
background: '#aaa',
});
};
// pause scrolling
scroller.pause = function() {
going = false;
button.onclick = scroller.go;
button.innerHTML = "play";
style(button, {
background: '#3b2',
});
};
// create button
button.innerHTML = "play";
style(button, {
position: 'fixed',
bottom: '4px',
right: '4px',
zIndex: '100',
fontSize: '11px',
padding: '2px 4px',
background: '#3b2',
color: '#fff',
lineHeight: '13px',
fontWeight: 'bold',
border: '1px solid #ccc',
cursor: 'pointer'
});
function style(el, obj) {
for (k in obj) {
el.style[k] = obj[k];
}
};
document.body.appendChild(button);
button.onclick = scroller.go;
return scroller;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment