js.anchor
Version:
Click and go to target. Pretty simple with only ~2KB and without dependencies.
1 lines • 1.9 kB
JavaScript
!function(t,n){var e=function(){return t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||function(n){t.setTimeout(n,1e3/60)}}(),o=function(t){t=t||{};for(var n=1;n<arguments.length;n++){var e=arguments[n];if(e)for(var r in e)e.hasOwnProperty(r)&&("object"==typeof e[r]?t[r]=o(t[r],e[r]):t[r]=e[r])}return t},r=function(t){var e=this,r={easings:{easeInOutQuad:function(t,n,e,o){return t/=o/2,1>t?e/2*t*t+n:(t--,-e/2*(t*(t-2)-1)+n)},easeInCubic:function(t,n,e,o){var r=(t/=o)*t*t;return n+e*r},inOutQuintic:function(t,n,e,o){var r=(t/=o)*t,i=r*t;return n+e*(6*i*r+-15*r*r+10*i)}}};return this.anchors=n.querySelectorAll("[data-anchor]"),this.opts=o({},r,t),{init:function(){e.bindAnchors()}}};r.prototype={bindAnchors:function(){var t=this;[].slice.call(t.anchors).forEach(function(e){e.addEventListener("click",function(e){e.preventDefault();var o=n.querySelector(this.getAttribute("data-anchor")),r=t.getOffset(o)||0,i=this.getAttribute("data-anchor-offset")||0,a=this.getAttribute("data-anchor-duration")||800,c=this.getAttribute("data-anchor-callback"),u=this.getAttribute("data-anchor-easing")||"easeInOutQuad";t.scrollTo(r.top-parseInt(i),t.executeFunctionByName.bind(this,c),a,t.opts.easings[u])})})},executeFunctionByName:function(n){if(n){var e=t[n];"function"==typeof e&&e.apply(null)}},getOffset:function(t){var n=0,e=0;if(t.offsetParent)do n+=t.offsetLeft,e+=t.offsetTop;while(t=t.offsetParent);return{0:n,1:e,left:n,top:e,length:2}},position:function(){return n.documentElement.scrollTop||n.body.parentNode.scrollTop||n.body.scrollTop},move:function(t){n.documentElement.scrollTop=t,n.body.parentNode.scrollTop=t,n.body.scrollTop=t},scrollTo:function(t,n,o,r){var i=this,a=i.position(),c=t-a,u=0,s=20,o="undefined"==typeof o?500:o,f=function(){u+=s;var t=r(u,a,c,o);i.move(t),o>u?e(f):n&&"function"==typeof n&&n()};f()}},t.Anchor=r}(window,document);