var btnAnchor2 = document.querySelectorAll('main .btn_item a[href*="#"]'); Array.prototype.slice.call(btnAnchor2).forEach(function(ele, index) { ele.addEventListener('click', function(e) { var headerWrap = document.querySelector('header .primary-section'); var href = this.getAttribute("href"); var getHash = href.split('#')[1]; var elem = document.querySelector("#"+getHash); var headerHeight = headerWrap.offsetHeight; var newOff = elem.offsetTop - headerHeight; console.log(headerHeight + 'header-height '); console.log( newOff +' off'); smoothScrollBackToTop(e, newOff); e.stopPropagation(); e.preventDefault(); }); }); function smoothScrollBackToTop(e, targetPos=0) { e.preventDefault(); var targetPosition = targetPos; var startPosition = window.pageYOffset; var distance = targetPosition - startPosition; var duration = 750; var start = null; window.requestAnimationFrame(step); function step(timestamp) { if (!start) start = timestamp; var progress = timestamp - start; window.scrollTo(0, easeInOutCubic(progress, startPosition, distance, duration)); if (progress < duration) window.requestAnimationFrame(step); } } function easeInOutCubic(t, b, c, d) { t /= d/2; if (t < 1) return c/2*t*t*t + b; t -= 2; return c/2*(t*t*t + 2) + b; };
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter