Skip to content

Instantly share code, notes, and snippets.

@AntonLitvin
Last active August 26, 2021 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AntonLitvin/6bf512c6735c490903a2e9d335db5c34 to your computer and use it in GitHub Desktop.
Save AntonLitvin/6bf512c6735c490903a2e9d335db5c34 to your computer and use it in GitHub Desktop.
document.querySelectorAll('a[href^="#"]').forEach(function (el) {
el.onclick = function (e) {
e.preventDefault();
var hash = this.getAttribute('href');
var target = document.querySelector(hash);
var headerOffset = 100;
var elementPosition = target.offsetTop;
var offsetPosition = elementPosition - headerOffset;
window.scrollTo({
top: offsetPosition,
behavior: 'smooth'
});
};
});
// Navs and blocks must be linked with ancors
$(document).on('click', 'a[href^="#"]', function (e) {
e.preventDefault();
var headerHeight = $('.site-header').outerHeight();
var elementClick = $(this).attr('href');
if ($(elementClick).length != 0) { // проверка существования элемента
var destination = $(elementClick).offset().top - headerHeight;
$('html, body').animate({ scrollTop: destination }, 500);
}
});
// Scroll to block
$('.header-nav a').on('click', function () {
var headerHeight = $('.page-header').outerHeight();
var elementClick = $(this).attr('href');
if ($(elementClick).length != 0) { // проверка существования элемента
var destination = $(elementClick).offset().top - headerHeight;
$('html, body').animate({ scrollTop: destination }, 1000);
}
return false;
});
//Another script
$(document).on('click', 'a[href*=\\#]', function() {
var headerHeight = $('.page-header').outerHeight();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: (target.offset().top - headerHeight)
}, 1000);
return false;
}
}
});
//Another one
$('.main-menu a').on('click', function () {
var el = $(this);
var dest = el.attr('href');
if (dest !== undefined && dest !== '') {
$('html').animate({ scrollTop: $(dest).offset().top }, 500);
}
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment