Created
January 11, 2021 16:15
-
-
Save timn5835/39a98635ab06fb9d1cc65a33f84353ce to your computer and use it in GitHub Desktop.
[Animate Scroll] #js #scroll
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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