Skip to content

Instantly share code, notes, and snippets.

@wayferer
Last active May 27, 2019 19:19
Show Gist options
  • Save wayferer/8845757 to your computer and use it in GitHub Desktop.
Save wayferer/8845757 to your computer and use it in GitHub Desktop.
JS scroll to anchor
//requires helpers.js
function zScrollToAnimate(el,from,to,time){
var start=new Date().getTime();
var timer=setInterval(function(){
var step=Math.min(1,(new Date().getTime()-start)/time);
el.scrollTop=from+step*(to-from);
//el.scrollTo(0,from+step*(to-from));
if(step==1){clearInterval(timer);}
},25);
}
/*function scrollToSection(event){
event.preventDefault ? event.preventDefault():event.returnValue=false;
if(typeof event.target!='undefined'){targetElement=event.target;}
else{targetElement=window.event.srcElement;}
var windowScrollPosition=document.body.scrollTop || document.documentElement.scrollTop;
var scrollTo=windowScrollPosition+zQA(event.target.getAttribute('href'))[0].getBoundingClientRect().top-76;
zScrollToAnimate(window,windowScrollPosition,scrollTo,250);
}*/
if(zQ('.js-scrollToAnchor')){
for(i=0;i<zQA('.js-scrollToAnchor').length;i++){
zBindEvent(zQA('.js-scrollToAnchor')[i],"click",function(e){
var currentEl=zGetCurrentTargetElement(e),
anchor=zQ(currentEl.getAttribute('href')),
container=body,
containerScrollPosition=container.scrollTop,
offset=zQ('.site-header').getBoundingClientRect().height;
scrollToAnchor(e,container,containerScrollPosition,anchor,offset,250);
})
}
}
function scrollToAnchor(e,container,containerScrollPosition,anchor,buffer,speed){
e.preventDefault ? e.preventDefault():e.returnValue=false;
var scrollTo=containerScrollPosition+anchor.getBoundingClientRect().top-buffer;
zScrollToAnimate(container,containerScrollPosition,scrollTo,speed);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment