How to create a smooth scrolling effect when clicking an anchor link
Using anchor links, you can make the page scroll towards the anchor and go to the section there. Is there a way to make that scrolling smooth? Yes, you can with 3 ways.
The new hotness in CSS3. This is a lot easier than every method listed on this page and requires no Javascript. Just enter the below code into you css and all of a sudden links point to locations inside you own page will have a smooth scrolling animation.
Add scroll-behavior: smooth to theelement to enable smooth scrolling for the whole page (note: it is also possible to add it to a specific element/scroll container):
1 2 3 | html { scroll-behavior: smooth; } |
There is also a native JavaScript version of smooth scrolling, like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // Scroll to specific values // scrollTo is the same window.scroll({ top: 2500, left: 0, behavior: 'smooth' <pre rel="HTML"><code markup="tt" class="language-markup"> }); // Scroll certain amounts from current position window.scrollBy({ top: 100, // could be negative value left: 0, behavior: 'smooth' }); // Scroll to a certain element document.querySelector('.link').scrollIntoView({ behavior: 'smooth' }); |
jQuery can also do this. Here’s the code to perform a smooth page scroll to an anchor on the same page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | // Select all links with hashes $('a[href*="#"]') // Remove links that don't actually link to anything .not('[href="#"]') .not('[href="#0"]') .click(function(event) { // On-page links if ( location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname ) { // Figure out element to scroll to var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); // Does a scroll target exist? if (target.length) { // Only prevent default if animation is actually gonna happen event.preventDefault(); $('html, body').animate({ scrollTop: target.offset().top }, 1000, function() { // Callback after animation // Must change focus! var $target = $(target); $target.focus(); if ($target.is(":focus")) { // Checking if the target was focused return false; } else { $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable $target.focus(); // Set focus again }; }); } } }); |