Smooth Scroll Javascript
Sun Sep 24 2023 15:01:30 GMT+0000 (Coordinated Universal Time)
Saved by
@sagarmaurya19
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;
};
content_copyCOPY
Comments