Smooth Scrolling on Anchor Click

jQuery javascript

This jUqery snipped allows, that when clicked on an anchor tag something.com#anchor, to scroll to it with an animation

$('a[href^="#"]').on('click', function(e) { e.preventDefault() $(document).off("scroll") var target = this.hash var menu = target $target = $(target) $('html, body').stop().animate({ 'scrollTop': $target.offset().top // optional: subtract navigation-height }, 1000, 'swing', function() { window.location.hash = target $(document).on("scroll", onscroll) }) })

Of course this could be done with plain JavaScript as well.

document.addEventListener('click', function(e){ if (e.which == 2 || e.button == 4) return for (var element, i = 0; element = e.path[i]; i++) { if (element.tagName === 'A' && element.href && element.href[0] === '#') { e.preventDefault() window.history.replaceState(undefined, undefined, element.href) return scrollTo( document.getElementById( element.href.split('#')[1] ) ) } } }) function scrollTo(target) { var origin = window.pageYOffset var timeOrigin = Date.now() var change = target.offsetTop - window.pageYOffset - 10 var durration = Settings.scrollSpeed var pageHeight = window.innerHeight + window.pageYOffset var easeOutCubic = function(t, b, c, d) { t /= d;t--;return c * (t * t * t + 1) + b } ;(function update() { var now = Date.now() var progress = easeOutCubic(now - timeOrigin, origin, change, durration) // if still time && not reached the bottom if (timeOrigin + durration > now && (change > 0 || pageHeight < document.body.offsetHeight)) { requestAnimationFrame(update) window.scrollTo(window.scrollX, progress) } else window.scrollTo(window.scrollX, origin + change) }()) }

Reference

No known

History May 08, 2017