Skip to content

Instantly share code, notes, and snippets.

@maksimerohin
Last active December 25, 2020 14:19
Show Gist options
  • Save maksimerohin/75b6bb4e29e714be66bbf146470db284 to your computer and use it in GitHub Desktop.
Save maksimerohin/75b6bb4e29e714be66bbf146470db284 to your computer and use it in GitHub Desktop.
Scroll To
var linkNav = document.querySelectorAll('[href^="#"]'), //выбираем все ссылки к якорю на странице
V = 1 // скорость, может иметь дробное значение через точку (чем меньше значение - тем больше скорость)
for (var i = 0; i < linkNav.length; i++) {
linkNav[i].addEventListener('click', function (e) { //по клику на ссылку
e.preventDefault() //отменяем стандартное поведение
var w = window.pageYOffset, // производим прокрутка прокрутка
hash = this.href.replace(/[^#]*(.*)/, '$1') // к id элемента, к которому нужно перейти
t = document.querySelector(hash).getBoundingClientRect().top, // отступ от окна браузера до id
start = null
requestAnimationFrame(step) // подробнее про функцию анимации [developer.mozilla.org]
function step (time) {
if (start === null) start = time
var progress = time - start,
r = (t < 0 ? Math.max(w - progress / V, w + t) : Math.min(w + progress / V, w + t))
window.scrollTo(0, r)
if (r != w + t) {
requestAnimationFrame(step)
} else {
location.hash = hash // URL с хэшем
}
}
}, false)
}
function meScrollTo (id, speed) {
if (speed === undefined) {
speed = 1100;
}
var destination = $(id).offset().top - $('.site-header').height() - 10;
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
customScrollTo(destination, 100);
} else {
$('body,html').animate({ scrollTop: destination }, speed);
return false;
}
};
function customScrollTo(to, duration) {
var start = $(window).scrollTop(),
change = to - start,
currentTime = 0,
increment = 20;
var animateScroll = function(){
currentTime += increment;
var val = Math.easeInOutQuad(currentTime, start, change, duration);
window.scrollTo(0,val);
if(currentTime < duration) {
setTimeout(animateScroll, increment);
}
};
animateScroll();
};
Math.easeInOutQuad = function (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
};
$('.js-scroll').click(function(e) {
e.preventDefault();
var id = $(this).attr('href');
meScrollTo(id);
});
@maksimerohin
Copy link
Author

window.scrollTo(0, destination);
Работает для iOS, но прокручивает не плавно.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment