Skip to content

Instantly share code, notes, and snippets.

@timn5835
Created January 11, 2021 16:15
Show Gist options
  • Save timn5835/39a98635ab06fb9d1cc65a33f84353ce to your computer and use it in GitHub Desktop.
Save timn5835/39a98635ab06fb9d1cc65a33f84353ce to your computer and use it in GitHub Desktop.
[Animate Scroll] #js #scroll
// ANIMATE ANCHOR SCROLL
const $root = $('html, body');
function animateScroll(yPos, speed) {
$root.animate({
scrollTop: yPos
}, speed);
}
// Stops the page load and animates scroll
$('ul#main-menu').on('click', 'a[href^="#"]', function(e) {
e.preventDefault();
let hash = $(this).attr('href'),
$target = $(''+hash),
yPos = $target.offset().top+'px';
animateScroll(yPos, 650);
// GA Custom Click Tracking
gtag('event','Anchor Click',{'event_category':'clicktrack','event_label':$(this).html()});
// window.location.hash = hash;
})
// Remove the leading slash on the homepage links so page doesn't load
$('body.home ul#main-menu a[href^="/#"]').each(function(e){
var href = $(this).attr('href');
if (href.indexOf("#")) {
href = href.replace('/','');
}
$(this).attr('href',href);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment