1//add smooth scrolling when clicking any anchor link
2document.querySelectorAll('a[href^="#"]').forEach(anchor => {
3 anchor.addEventListener('click', function (e) {
4 e.preventDefault();
5 document.querySelector(this.getAttribute('href')).scrollIntoView({
6 behavior: 'smooth'
7 });
8 });
9});
10//<a href="#someOtherElementID"> Go to Other Element Smoothly </a>
1html {
2 scroll-behavior: smooth;
3}
4
5/* No support in IE, or Safari
6You can use this JS polyfill for those */
7http://iamdustan.com/smoothscroll/
8
1// Select all links with hashes
2$('a[href*="#"]')
3 // Remove links that don't actually link to anything
4 .not('[href="#"]')
5 .not('[href="#0"]')
6 .click(function(event) {
7 // On-page links
8 if (
9 location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
10 &&
11 location.hostname == this.hostname
12 ) {
13 // Figure out element to scroll to
14 var target = $(this.hash);
15 target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
16 // Does a scroll target exist?
17 if (target.length) {
18 // Only prevent default if animation is actually gonna happen
19 event.preventDefault();
20 $('html, body').animate({
21 scrollTop: target.offset().top
22 }, 1000, function() {
23 // Callback after animation
24 // Must change focus!
25 var $target = $(target);
26 $target.focus();
27 if ($target.is(":focus")) { // Checking if the target was focused
28 return false;
29 } else {
30 $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
31 $target.focus(); // Set focus again
32 };
33 });
34 }
35 }
36 });
1/* ==========================================================================
2 Smooth scroll
3 ========================================================================== */
4$('a[href*=#]:not([href=#])').on('click', function() {
5 if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {
6 var target = $(this.hash);
7 target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
8 if (target.length) {
9 $('html,body').animate({
10
11 scrollTop: (target.offset().top - 40)
12 }, 1000);
13 return false;
14 }
15 }
16});