Scroll smoothly to specific element on page

121,741

Solution 1

Just made this javascript only solution below.

Simple usage:

EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);

Engine object (you can fiddle with filter, fps values):

/**
 *
 * Created by Borbás Geri on 12/17/13
 * Copyright (c) 2013 eppz! development, LLC.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */


var EPPZScrollTo =
{
    /**
     * Helpers.
     */
    documentVerticalScrollPosition: function()
    {
        if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
        if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
        if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
        return 0; // None of the above.
    },

    viewportHeight: function()
    { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },

    documentHeight: function()
    { return (document.height !== undefined) ? document.height : document.body.offsetHeight; },

    documentMaximumScrollPosition: function()
    { return this.documentHeight() - this.viewportHeight(); },

    elementVerticalClientPositionById: function(id)
    {
        var element = document.getElementById(id);
        var rectangle = element.getBoundingClientRect();
        return rectangle.top;
    },

    /**
     * Animation tick.
     */
    scrollVerticalTickToPosition: function(currentPosition, targetPosition)
    {
        var filter = 0.2;
        var fps = 60;
        var difference = parseFloat(targetPosition) - parseFloat(currentPosition);

        // Snap, then stop if arrived.
        var arrived = (Math.abs(difference) <= 0.5);
        if (arrived)
        {
            // Apply target.
            scrollTo(0.0, targetPosition);
            return;
        }

        // Filtered position.
        currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);

        // Apply target.
        scrollTo(0.0, Math.round(currentPosition));

        // Schedule next tick.
        setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
    },

    /**
     * For public use.
     *
     * @param id The id of the element to scroll to.
     * @param padding Top padding to apply above element.
     */
    scrollVerticalToElementById: function(id, padding)
    {
        var element = document.getElementById(id);
        if (element == null)
        {
            console.warn('Cannot find element with id \''+id+'\'.');
            return;
        }

        var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
        var currentPosition = this.documentVerticalScrollPosition();

        // Clamp.
        var maximumScrollPosition = this.documentMaximumScrollPosition();
        if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;

        // Start animation.
        this.scrollVerticalTickToPosition(currentPosition, targetPosition);
    }
};

Solution 2

Super smoothly with requestAnimationFrame

For smoothly rendered scrolling animation one could use window.requestAnimationFrame() which performs better with rendering than regular setTimeout() solutions.

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);
    }
  })
}

For element's Y position use functions in other answers or the one in my below-mentioned fiddle.

I set up a bit more sophisticated function with easing support and proper scrolling to bottom-most elements: https://jsfiddle.net/s61x7c4e/

Solution 3

Question was asked 5 years ago and I was dealing with smooth scroll and felt giving a simple solution is worth it to those who are looking for. All the answers are good but here you go a simple one.

function smoothScroll(){
    document.querySelector('.your_class or #id here').scrollIntoView({
        behavior: 'smooth'
    });
}

just call the smoothScroll function on onClick event on your source element.

DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

Note: Please check compatibility here

3rd Party edit

Support for Element.scrollIntoView() in 2020 is this:

Region            full   + partial = sum full+partial Support
Asia              73.24% + 22.75%  = 95.98%
North America     56.15% + 42.09%  = 98.25%
India             71.01% + 20.13%  = 91.14%
Europe            68.58% + 27.76%  = 96.35%

scrollintoview support 2020-02-28

Solution 4

Smooth scrolling - look ma no jQuery

Based on an article on itnewb.com i made a demo plunk to smoothly scroll without external libraries.

The javascript is quite simple. First a helper function to improve cross browser support to determine the current position.

function currentYPosition() {
    // Firefox, Chrome, Opera, Safari
    if (self.pageYOffset) return self.pageYOffset;
    // Internet Explorer 6 - standards mode
    if (document.documentElement && document.documentElement.scrollTop)
        return document.documentElement.scrollTop;
    // Internet Explorer 6, 7 and 8
    if (document.body.scrollTop) return document.body.scrollTop;
    return 0;
}

Then a function to determine the position of the destination element - the one where we would like to scroll to.

function elmYPosition(eID) {
    var elm = document.getElementById(eID);
    var y = elm.offsetTop;
    var node = elm;
    while (node.offsetParent && node.offsetParent != document.body) {
        node = node.offsetParent;
        y += node.offsetTop;
    } return y;
}

And the core function to do the scrolling

function smoothScroll(eID) {
    var startY = currentYPosition();
    var stopY = elmYPosition(eID);
    var distance = stopY > startY ? stopY - startY : startY - stopY;
    if (distance < 100) {
        scrollTo(0, stopY); return;
    }
    var speed = Math.round(distance / 100);
    if (speed >= 20) speed = 20;
    var step = Math.round(distance / 25);
    var leapY = stopY > startY ? startY + step : startY - step;
    var timer = 0;
    if (stopY > startY) {
        for ( var i=startY; i<stopY; i+=step ) {
            setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
            leapY += step; if (leapY > stopY) leapY = stopY; timer++;
        } return;
    }
    for ( var i=startY; i>stopY; i-=step ) {
        setTimeout("window.scrollTo(0, "+leapY+")", timer * speed);
        leapY -= step; if (leapY < stopY) leapY = stopY; timer++;
    }
    return false;
}

To call it you just do the following. You create a link which points to another element by using the id as a reference for a destination anchor.

<a href="#anchor-2" 
   onclick="smoothScroll('anchor-2');">smooth scroll to the headline with id anchor-2<a/>
...
...  some content
...
<h2 id="anchor-2">Anchor 2</h2>

Copyright

In the footer of itnewb.com the following is written: The techniques, effects and code demonstrated in ITNewb articles may be used for any purpose without attribution (although we recommend it) (2014-01-12)

Solution 5

You could also check this great Blog - with some very simple ways to achieve this :)

https://css-tricks.com/snippets/jquery/smooth-scrolling/

Like (from the blog)

// 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' 
});

and you can also get the element "top" position like below (or some other way)

var e = document.getElementById(element);
var top = 0;

do {   
    top += e.offsetTop;
} while (e = e.offsetParent);

return top;
Share:
121,741

Related videos on Youtube

M P
Author by

M P

Updated on July 09, 2022

Comments

  • M P
    M P almost 2 years

    I want to have 4 buttons/links on the beginning of the page, and under them the content.

    On the buttons I put this code:

    <a href="#idElement1">Scroll to element 1</a>
    <a href="#idElement2">Scroll to element 2</a>
    <a href="#idElement3">Scroll to element 3</a>
    <a href="#idElement4">Scroll to element 4</a>
    

    And under links there will be content:

    <h2 id="idElement1">Element1</h2>
    content....
    <h2 id="idElement2">Element2</h2>
    content....
    <h2 id="idElement3">Element3</h2>
    content....
    <h2 id="idElement4">Element4</h2>
    content....
    

    It is working now, but cannot make it look more smooth.

    I used this code, but cannot get it to work.

    $('html, body').animate({
        scrollTop: $("#elementID").offset().top
    }, 2000);
    

    Any suggestions? Thank you.

    Edit: and the fiddle: http://jsfiddle.net/WxJLx/2/

    • MDEV
      MDEV almost 11 years
    • Or Duan
      Or Duan almost 11 years
      i have to ask, did you use the animate code inside an click event?
    • M P
      M P almost 11 years
      im afraid I dont know what are you asking me
    • dbanet
      dbanet almost 11 years
      $('#idElement1').onclick=function(){/*here is your smothscroll code*/}
    • dbanet
      dbanet almost 11 years
      also, don't forget to return false to disable the native scrolling
    • M P
      M P almost 11 years
      can you show me in that fiddle please: jsfiddle.net/WxJLx/2
    • surfmuggle
      surfmuggle almost 11 years
      It is unclear to me if you want to find a solution for smooth scrolling or if you want to know and understand why your code does not work.
  • M P
    M P almost 11 years
    So I would need to code like this: $('#id1').localScroll({ target:'#content1' });
  • M P
    M P almost 11 years
    In the mean time I made this fiddle: jsfiddle.net/WxJLx/15.. it is working in fiddle, but not on the wordpress. Can you check this source code, if you can spot any problems? Thank you: view-source:anchovyluxury.com/yachts/services
  • surfmuggle
    surfmuggle almost 11 years
    What have you tried to find the mistake? Are you familiar with the chrome dev tools - they make it super easy to spot errors: $('a[href^="#"]').click(function(){ in line 360 of anchovyluxury.com/yachts/services Have you any more questions regarding how to scroll smoothly?
  • M P
    M P almost 11 years
    I tried to put in that code which pops up window that jquery is working. And my code is working in the fiddle, so dont know where the problem is.
  • Lukas Liesis
    Lukas Liesis about 8 years
    Thanks, just saved me some time :) I also added to smoothScroll({eID, padding = 0}) and then stopY += padding; after let stopY = elmYPosition(eID); to have some padding around element and not to scroll to exact element
  • Lukas Liesis
    Lukas Liesis about 8 years
    and would have to import all jQuery lib to scroll. Better done with vanila js like other answers.
  • monners
    monners over 7 years
    Executing string as function.... :( Why not just: setTimeout(window.scrollTo.bind(null, 0, leapY), timer * speed);
  • Vahid Amiri
    Vahid Amiri over 7 years
    This worked perfectly for me. I just think it would be better with semicolons!
  • Dev_NIX
    Dev_NIX over 7 years
    Just doing a little library based on your source, linking here in the credits. Thank you!
  • Daniel Sawka
    Daniel Sawka over 7 years
    @Dev_NIX Glad I could help! Once I used sweet-scroll library but it somehow did not play well with React. You could reuse some API or code from that.
  • Admin
    Admin over 7 years
    just wanted to add - my aim was not to use any external libraries, there is no point to load huge jquery just for page scroll ;-)
  • BrandonReid
    BrandonReid over 7 years
    This is way sick. Thanks!
  • Subham Tripathi
    Subham Tripathi about 7 years
    Hey, Thanks for the solution. :) Can you please tell me what's the use of variable window._TO. I'm unable to figure what it does and why are we using clearTimeout . I have removed clearTimeout and it works perfectly fine for me.
  • Admin
    Admin about 7 years
    @Subham Tripathi if you call the function again before it finishes it will behave quite bad - because it will keep moving to the first point and if the second call want to move it to different point it will be just there and back - forever
  • Karedia Noorsil
    Karedia Noorsil over 5 years
    scrollIntoView with 'smooth' has no support for IE, EDGE and Safari (2018/09/28)
  • Sanjay Shr
    Sanjay Shr over 5 years
    @KarediaNoorsil Thank you for reporting, Updated my answer.
  • n8jadams
    n8jadams about 4 years
    Best answer in 2020.
  • Naskalin
    Naskalin about 3 years
    Thanks, ur best! :)
  • Ralph David Abernathy
    Ralph David Abernathy over 2 years
    How to offset scroll if website has sticky header, for example?
  • Adrian P.
    Adrian P. over 2 years
    Safari is like IE. Some people are still using it by inertia or lack of knowledge.
  • Dinith Rukshan Kumara
    Dinith Rukshan Kumara over 2 years
    I think this is the best answer. I found many other solutions not work well in some mobile devices. Stuck for some time & then start scroll. This is the only one that doesn't happen.
  • Arunjith R S
    Arunjith R S over 2 years
    The best answer for the solution. <3
  • Ben Racicot
    Ben Racicot about 2 years
    We should be dropping browsers who don't have features like this. Or ship a polyfill if business forces us to support. Either way this is the answer to the OPs question in 2022.