Scroll smoothly to specific element on page

Asked
Active3 hr before
Viewed126 times

8 Answers

smoothlyscrollspecific
90%

Make sure to add a click event handler for each link that should do smooth scrolling,reference jQuery and the scrollTo Plugin,create the elements you want to scroll to,Create links where href points to another elements.id

A basic example looks like this. Function step is called for browser's every animation frame and allows for better time management of repaints, and thus increasing performance.

function doScrolling(elementY, duration) {
   var startingY = window.pageYOffset;
   var diff = elementY - startingY;
   var start;

   // Bootstrap our animation - it will get called right before next frame shall be rendered.
   window.requestAnimationFrame(function step(timestamp) {
      if (!start) start = timestamp;
      // Elapsed milliseconds since start of scrolling.
      var time = timestamp - start;
      // Get percent of completion in range [0, 1].
      var percent = Math.min(time / duration, 1);

      window.scrollTo(0, startingY + diff * percent);

      // Proceed with animation as long as we wanted it to.
      if (time < duration) {
         window.requestAnimationFrame(step);
      }
   })
}
load more v
88%

Add scroll-behavior: smooth to the <html> element to enable smooth scrolling for the whole page (note: it is also possible to add it to a specific element/scroll container):,Note: Remove the scroll-behavior property to remove smooth scrolling.,The numbers in the table specify the first browser version that fully supports the scroll-behavior property.,Tip: Read more about the scroll-behavior property in our CSS Reference: CSS scroll-behavior Property.

Smooth Scrolling

Add scroll-behavior: smooth to the <html> element to enable smooth scrolling for the whole page (note: it is also possible to add it to a specific element/scroll container):

scroll - behavior: smooth
load more v
72%

jQuery can also do this. Here’s the code to perform a smooth page scroll to an anchor on the same page. It has some logic built in to identify those jump links, and not target other links.,I added this to my page, and yes, it now smoothly scrolls to given anchor position within the same page.,arrange for the smooth scrool ios,Redirects to the gallery page and scroll to id=”06″

Hey! Before you go too far down the rabbit hole of JavaScript-based smooth scrolling, know that there is a native CSS feature for this: scroll-behavior.

html {
   scroll - behavior: smooth;
}

And before you reach for a library like jQuery to help, there is also a native JavaScript version of smooth scrolling, like this:

// Scroll to specific values
// scrollTo is the same
window.scroll({
   top: 2500,
   left: 0,
   behavior: 'smooth'
});

// 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('.hello').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. It has some logic built in to identify those jump links, and not target other links.

// 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
               };
            });
         }
      }
   });
load more v
65%

The duration is a number of milliseconds. You can change it to a configurable option, but in this post, it's set as 800.,The ending point is the top distance of the target. It can be retrieved as target.getBoundingClientRect().top,Scroll to top of the page

ele.scrollIntoView({
   behavior: 'smooth'
});
load more v
75%

How to set smooth scroll after clicking the link using JavaScript ?,Scroll to the top of the page using JavaScript/jQuery,There are two methods to smoothly scroll a web page after clicking the anchor link which are discussed below:,How to scroll to an element inside a div using javascript?

40%

Each section will have an id whose value will match the href value of a menu link. This association (what we refer to as a fragment identifier) will allow us to jump to specific parts of our page.,That’s all we need so far! If we now click on a specific link, we’ll immediately jump to the relevant page section. ,Coming up next, we’ll apply some styles to the sections. Most importantly, we’ll ensure that they will be tall enough, so there’s adequate scrolling inside the page for the effect:,First, we’ll use the scroll() method. The logic for this approach is similar to the previous jQuery implementation. 

Here’s the HTML:

<div class="container">
   ...
   <header class="page-header">
      <nav>
         <ul>
            <li>
               <a href="#...">...</a>
            </li>
            <!-- more links -->
         </ul>
      </nav>
      <div class="header-text">...</div>
   </header>
</div>
<section class="section" id="">...</section>
<section class="section" id="">...</section>
<section class="section" id="">...</section>
<section class="section" id="">...</section>
load more v
22%

The Element interface's scrollIntoView() method scrolls the element's parent container such that the element on which scrollIntoView() is called is visible to the user. ,Report a problem with this content on GitHub,Element.scrollIntoView(),Element.scrollIntoViewIfNeeded()

element.scrollIntoView();
element.scrollIntoView(alignToTop); // Boolean parameter
element.scrollIntoView(scrollIntoViewOptions); // Object parameter
load more v
60%

This parameter scrollIntoViewOptions is an object with the following properties :,behavior : This sets whether scrolling should be an animated one or an instant scroll to the element. It can have the following values :,The scrollIntoView method also accepts a parameter through which you can set an animated scroll behavior and also customize its alignment.,end : Element is aligned at the right of the scrollable parent.

Quick Sample Code

// element which needs to be scrolled to
var element = document.querySelector("#post-container");

// scroll to element
element.scrollIntoView();
load more v

Other "smoothly-scroll" queries related to "Scroll smoothly to specific element on page"