Skip to content

Instantly share code, notes, and snippets.

@sketchpunk
Last active April 24, 2019 17:09
Show Gist options
  • Save sketchpunk/5e5ad57089cc67655f8ae164e96434f9 to your computer and use it in GitHub Desktop.
Save sketchpunk/5e5ad57089cc67655f8ae164e96434f9 to your computer and use it in GitHub Desktop.
const SCROLL_TOP_OFFSET = -19;
class Scroll{
static next(){
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if( ! this.ary ){
let elm, root = document.getElementById("ContentArea");
this.ary = new Array();
for( let i=0; i < root.childNodes.length; i++ ){
if( root.childNodes[ i ].nodeType != 1 ) continue;
elm = root.childNodes[ i ];
this.ary.push( elm.offsetTop - elm.scrollTop + SCROLL_TOP_OFFSET );
}
this.ary[0] = 0;
//console.log( this.ary );
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let i, pos=0,
cpos = window.pageYOffset;
for( i=this.ary.length - 1; i >= 0; i-- ){
if( cpos >= this.ary[i] ){
pos = ( i+1 < this.ary.length )? this.ary[i+1] : 0;
break;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//console.log("SCROLL TO", pos );
this.to = pos;
this.task.start();
}
static first(){
this.to = 0;
this.task.start();
}
}
Scroll.idx = 0;
Scroll.ary = null;
Scroll.to = 0;
Scroll.task = new RunTillTrue( 15, function(){
let py = window.pageYOffset,
dif = Scroll.to - py;
if( Math.abs(dif) <= 1 ){ window.scrollTo( 0, Scroll.to ); return true; }
let offset = ( dif < 0 )? Math.floor( dif * 0.04 ) : Math.ceil( dif * 0.04 );
window.scrollTo( 0, py + offset );
return false;
});
class RunTillTrue{
constructor( s, func = null ){
this.sec = s;
this.thread = null;
this.task = func;
this.active = false;
this.run = ()=>{
if( !this.active || this.task() == true ) this.stop();
};
}
stop(){
this.active = false;
clearInterval( this.thread );
this.thread = null;
}
start(){
if( !this.thread ) clearInterval( this.thread );
this.active = true;
this.thread = setInterval( this.run, this.sec );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment