698

I have a list of questions. When I click on the first question, it should automatically take me to a specific element at the bottom of the page.

How can I do this with jQuery?

3

32 Answers 32

1345

jQuery isn't necessary. Most of the top results I got from a Google search gave me this answer:

window.scrollTo(0, document.body.scrollHeight);

Where you have nested elements, the document might not scroll. In this case, you need to target the element that scrolls and use its scroll height instead.

nestedElement.scrollTo(0, nestedElement.scrollHeight);

Some additional sources you can take a look at:

11
  • 63
    Didn't work for me. I did this: element.scrollTop = element.scrollHeight.
    – Esamo
    Aug 17, 2015 at 14:54
  • 9
    May 4, 2016: Please note that that the "scrollTo" function is experimental and does not work in all browsers.
    – corgrath
    May 4, 2016 at 5:31
  • 1
    scrollto did not work on my browser, I came across this link below stackoverflow.com/questions/8917921/… which is very useful because the solutions work across the browsers I tried. Apr 12, 2017 at 2:36
  • 1
    for a separate element, this is working solution: document.querySelector(".scrollingContainer").scrollTo(0,document.querySelector(".scrollingContainer").scrollHeight);
    – mPrinC
    Nov 10, 2018 at 7:10
  • 3
    This should work too: objectSelector.scrollTo({ top: objectSelector.scrollHeight }). Understanding that objectSelector is the element returned by document.getElementById. PD: adding behavior: 'smooth' in the scrollTo method options set up a predefined scrolling animation.
    – KBeDev
    Aug 19, 2020 at 20:02
194

To scroll entire page to the bottom:

const scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;

You can view the demo here

To scroll a specific element to the bottom:

const scrollToBottom = (id) => {
    const element = document.getElementById(id);
    element.scrollTop = element.scrollHeight;
}

Here is the demo

And here's how it works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

UPDATE: Latest versions of Chrome (61+) and Firefox does not support scrolling of body, see: https://dev.opera.com/articles/fixing-the-scrolltop-bug/

2
  • 2
    The solution works with Chrome, Firefox, Safari and IE8+. Check out this link for more detail quirksmode.org/dom/w3c_cssom.html
    – Tho
    Jan 26, 2016 at 8:49
  • 1
    @luochenhuan, I've just fixed the sample code by using "document.scrollingElement" instead of "document.body", see above Apr 17, 2018 at 4:35
100

Vanilla JS implementation:

element.scrollIntoView(false);

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

10
  • 3
    with jQuery $('#id')[0].scrollIntoView(false); Nov 5, 2014 at 21:18
  • 4
    at the moment it's Firefox only though
    – tim-we
    Jun 5, 2015 at 10:37
  • Works in newer versions of Chrome now, but some of the extra options (like smooth scrolling) don't seem to be implemented yet. Feb 17, 2016 at 16:42
  • I added an empty div at the end of the page and used the id of that div. Worked perfectly.
    – Nisba
    Mar 6, 2018 at 16:28
  • 19
    Even better: element.scrollIntoView({behavior: "smooth"});
    – blalond
    May 24, 2018 at 0:45
41

You can use this to go down the page in an animation format.

$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");
0
39

one liner to smooth scroll to the bottom

window.scrollTo({ left: 0, top: document.body.scrollHeight, behavior: "smooth" });

To scroll up simply set top to 0

1
  • 1
    This solution doesn't work in IE. Is there any workout that we can add to make this work in IE as well. Dec 18, 2020 at 10:44
35

Below should be the cross browser solution. It has been tested on Chrome, Firefox, Safari and IE11

window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight);

window.scrollTo(0,document.body.scrollHeight); doesn't work on Firefox, at least for Firefox 37.0.2

3
  • 1
    It does work in Firefox 62.0.3, but I've got no clue when they fixed that.
    – zb226
    Oct 18, 2018 at 11:43
  • window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight); - The scroll is not smooth. How will make the scrolling smooth @PixelsTech Dec 18, 2020 at 9:27
  • You can add options to scrolling
    – maazakn
    Aug 9, 2021 at 21:10
22

CSS-Only?!

An interesting CSS-only alternative:

display: flex; 
flex-direction: column-reverse;

  /* ...probably usually along with: */

overflow-y: scroll;  /* or hidden or auto */
height: 100px; /* or whatever */

It's not bullet-proof but I've found it helpful in several situations.

Documentation: flex, flex-direction, overflow-y


Demo:

var i=0, foo='Lorem Ipsum & foo in bar or blah ! on and'.split(' ');
setInterval(function(){demo.innerHTML+=foo[i++%foo.length]+' '},200)
#demo{ display:flex;
       flex-direction:column-reverse;
       overflow-y:scroll;
       width:150px; 
       height:150px;
       border:3px solid black; }
body{ font-family:arial,sans-serif; 
      font-size:15px; }
Autoscrolling demo:🐾
<div id='demo'></div>

1
  • 3
    Be aware that this will create a disconnect between the visual presentation and DOM order when using multiple elements – like paragraphs – to display the text, which will negatively affect users using screen readers. This type of user will not have access to the correct reading order. Apr 19, 2022 at 17:39
19

Sometimes the page extends on scroll to buttom (for example in social networks), to scroll down to the end (ultimate buttom of the page) I use this script:

var scrollInterval = setInterval(function() { 
    document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);

And if you are in browser's javascript console, it might be useful to be able to stop the scrolling, so add:

var stopScroll = function() { clearInterval(scrollInterval); };

And then use stopScroll();.

If you need to scroll to particular element, use:

var element = document.querySelector(".element-selector");
element.scrollIntoView();

Or universal script for autoscrolling to specific element (or stop page scrolling interval):

var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
    var element = document.querySelector(".element-selector");
    if (element) { 
        // element found
        clearInterval(scrollInterval);
        element.scrollIntoView();
    } else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) { 
        // no element -> scrolling
        notChangedStepsCount = 0;
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    } else if (notChangedStepsCount > 20) { 
        // no more space to scroll
        clearInterval(scrollInterval);
    } else {
        // waiting for possible extension (autoload) of the page
        notChangedStepsCount++;
    }
}, 50);
2
  • let size = ($("div[class*='card-inserted']")).length; ($("div[class*='card-inserted']"))[size -1].scrollIntoView(); Jul 26, 2018 at 3:36
  • @nobjta_9x_tq this will work only if the page is loaded up to the end.
    – Konard
    Apr 22, 2021 at 11:39
14

you can do this too with animation, its very simple

$('html, body').animate({
   scrollTop: $('footer').offset().top
   //scrollTop: $('#your-id').offset().top
   //scrollTop: $('.your-class').offset().top
}, 'slow');

hope helps, thank you

13

You can use this function wherever you need to call it:

function scroll_to(div){
   if (div.scrollTop < div.scrollHeight - div.clientHeight)
        div.scrollTop += 10; // move down

}

jquery.com: ScrollTo

1
  • For me, document.getElementById('copyright').scrollTop += 10 doesn't work (in latest Chrome)... remains zero...
    – Kyle Baker
    Nov 4, 2016 at 16:27
10

So many answers trying to calculate the height of the document. But it wasn't calculating correctly for me. However, both of these worked:

jquery

    $('html,body').animate({scrollTop: 9999});

or just js

    window.scrollTo(0,9999);
5
  • 2
    LOL "worked". What if the document is longer than 9999? May 18, 2020 at 9:55
  • 3
    @DanDascalescu 99999
    – Andrew
    May 18, 2020 at 16:56
  • 1
    What if the document is longer than 99999?! Oct 29, 2020 at 1:32
  • 2
    @BrendonMuir If the document is longer than 99999 you can define a javascript variable above the javascript code in the answer that gets the dynamic height of the document and use that variable instead of the hard coded 99999
    – nviens
    Nov 24, 2020 at 14:21
  • 1
    Sorry @nviens, I was just being silly, following on from DanDascalescu :D Nov 25, 2020 at 3:55
9

Here is a method that worked for me:

Expected outcome:

  • No scroll animation
  • Loads at bottom of page on first load
  • Loads on bottom of page for all refreshes

Code:

<script>
    function scrollToBottom() {
        window.scrollTo(0, document.body.scrollHeight);
    }
    history.scrollRestoration = "manual";
    window.onload = scrollToBottom;
</script>

Why this may work over other methods:

Browsers such as Chrome have a built-in preset to remember where you were on the page, after refreshing. Just a window.onload doesn't work because your browser will automatically scroll you back to where you were before refreshing, AFTER you call a line such as:

window.scrollTo(0, document.body.scrollHeight);

That's why we need to add:

history.scrollRestoration = "manual";

before the window.onload to disable that built-in feature first.

References:

Documentation for window.onload: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

Documentation for window.scrollTo: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

Documentation for history.scrollRestoration: https://developer.mozilla.org/en-US/docs/Web/API/History/scrollRestoration

0
8

A simple way if you want to scroll down to a specific element.

Call this function whenever you want to scroll down.

function scrollDown() {
 document.getElementById('scroll').scrollTop =  document.getElementById('scroll').scrollHeight
}
ul{
 height: 100px;
 width: 200px;
 overflow-y: scroll;
 border: 1px solid #000;
}
<ul id='scroll'>
<li>Top Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Something Here</li>
<li>Bottom Here</li>
<li style="color: red">Bottom Here</li>
</ul>

<br />

<button onclick='scrollDown()'>Scroll Down</button>

3
  • This is not simple, and requires creating a scroll element. May 18, 2020 at 9:57
  • @DanDascalescu You're right! but my code works I don't think it deserves down vote
    – Liam
    May 18, 2020 at 13:09
  • "Works" is not enough. All solutions on this page "work" to some extent. And there's a ton of them. How should a reader decide? May 19, 2020 at 1:03
6

You can attach any id to reference attribute href of link element:

<a href="#myLink" id="myLink">
    Click me
</a>

In the example above when user clicks Click me at the bottom of page, navigation navigates to Click me itself.

1
  • 1
    This did not for for me because it changes url and then my angular app redirects to something else!
    – heman123
    Jul 22, 2017 at 12:57
4

You may try Gentle Anchors a nice javascript plugin.

Example:

function SomeFunction() {
  // your code
  // Pass an id attribute to scroll to. The # is required
  Gentle_Anchors.Setup('#destination');
  // maybe some more code
}

Compatibility Tested on:

  • Mac Firefox, Safari, Opera
  • Windows Firefox, Opera, Safari, Internet Explorer 5.55+
  • Linux untested but should be fine with Firefox at least
4

Late to the party, but here's some simple javascript-only code to scroll any element to the bottom:

function scrollToBottom(e) {
  e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}
4

For Scroll down in Selenium use below code:

Till the bottom drop down, scroll till the height of the page. Use the below javascript code that would work fine in both, JavaScript and React.

JavascriptExecutor jse = (JavascriptExecutor) driver; // (driver is your browser webdriver object) 
jse.executeScript("window.scrollBy(0,document.body.scrollHeight || document.documentElement.scrollHeight)", "");
3

Here's my solution:

 //**** scroll to bottom if at bottom

 function scrollbottom() {
    if (typeof(scr1)!='undefined') clearTimeout(scr1)   
    var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
    if((scrollTop + window.innerHeight) >= scrollHeight-50) window.scrollTo(0,scrollHeight+50)
    scr1=setTimeout(function(){scrollbottom()},200) 
 }
 scr1=setTimeout(function(){scrollbottom()},200)
1
  • 1
    What... is even going on there? Care you explain your solution? Code-only answers are discouraged. May 18, 2020 at 9:55
3

Here's a fairly modern react/typescript-ish utility I am using:

export const scrollToBottom = () => {
  // Assume a react re-render may need to happen first
  setTimeout(() => {
    requestAnimationFrame(() => {
      window.scrollTo({
        top: document.documentElement.scrollHeight - window.innerHeight,
        left: 0,
        behavior: 'smooth',
      })
    })
  }, 3)
}

See browser support on smooth scrolling here: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#browser_compatibility

This could probably be turned into a hook:

export const useScrollToBottomWhen = (condition: boolean) => {
  useEffect(() => {
    if (condition) {
      window.scrollTo({
        top: document.documentElement.scrollHeight - window.innerHeight,
        left: 0,
        behavior: 'smooth',
      })
    }
  }, [condition]);
}
2

I have an Angular app with dynamic content and I tried several of the above answers with not much success. I adapted @Konard's answer and got it working in plain JS for my scenario:

HTML

<div id="app">
    <button onClick="scrollToBottom()">Scroll to Bottom</button>
    <div class="row">
        <div class="col-md-4">
            <br>
            <h4>Details for Customer 1</h4>
            <hr>
            <!-- sequence Id -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="ID">
            </div>
            <!-- name -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Name">
            </div>
            <!-- description -->
            <div class="form-group">
                <textarea type="text" style="min-height: 100px" placeholder="Description" ></textarea>
            </div>
            <!-- address -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Address">
            </div>
            <!-- postcode -->
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Postcode">
            </div>
            <!-- Image -->
            <div class="form-group">
                <img style="width: 100%; height: 300px;">
                <div class="custom-file mt-3">
                    <label class="custom-file-label">{{'Choose file...'}}</label>
                </div>
            </div>
            <!-- Delete button -->
            <div class="form-group">
                <hr>
                <div class="row">
                    <div class="col">
                        <button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to save">Save</button>
                        <button class="btn btn-success btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to update">Update</button>
                    </div>
                    <div class="col">
                        <button class="btn btn-danger btn-block" data-toggle="tooltip" data-placement="bottom" title="Click to remove">Remove</button>
                    </div>
                </div>
                <hr>
            </div>
        </div>
    </div>
</div>

CSS

body {
    background: #20262E;
    padding: 20px;
    font-family: Helvetica;
}

#app {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    transition: all 0.2s;
}

JS

function scrollToBottom() {
    scrollInterval;
    stopScroll;

    var scrollInterval = setInterval(function () {
        document.documentElement.scrollTop = document.documentElement.scrollHeight;
    }, 50);

    var stopScroll = setInterval(function () {
        clearInterval(scrollInterval);
    }, 100);
}

Tested on the latest Chrome, FF, Edge, and stock Android browser. Here's a fiddle:

https://jsfiddle.net/cbruen1/18cta9gd/16/

2

I found a trick to make it happen.

Put an input type text at the bottom of the page and call a jquery focus on it whenever you need to go at the bottom.

Make it readonly and nice css to clear border and background.

2

I gave up with scrollto but instead tried anchor approach:

<a href="#target_id_at_bottom">scroll to the bottom</a>

Along with this CSS charm:

html,
body {
    scroll-behavior: smooth;
}

Have a nice day!

2

If there is an ID in any kind of tag at or nearby where you want to scroll to, then all it takes is one line of JavaScript making use of the scrollIntoView function. For example, let's say your element in question is a DIV with the ID "mydiv1"

<div id="mydiv1">[your contents]</div>

then you would run the JavaScript command

document.getElementById("mydiv1").scrollIntoView();

No JQuery is necessary at all. Hope this helps.

2

using reac.js here is the working code

        //auto scroll to the bottom 
    useEffect(()=>{
      const chatHolder = document.getElementById('chats-wrapper')
       if(chatHolder) {
          chatHolder.scrollIntoView({behavior: "smooth"})
       }
  },[chats])
1

window.scrollTo(0,1e10);

always works.

1e10 is a big number. so its always the end of the page.

1

If any one searching for Angular

you just need to scroll down add this to your div

 #scrollMe [scrollTop]="scrollMe.scrollHeight"

   <div class="my-list" #scrollMe [scrollTop]="scrollMe.scrollHeight">
   </div>
1

This will guaranteed scroll to the bottom

Head Codes

<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script language="javascript" type="text/javascript">
function scrollToBottom() {
  $('#html, body').scrollTop($('#html, body')[0].scrollHeight);
}
</script>

Body code

<a href="javascript:void(0);" onmouseover="scrollToBottom();" title="Scroll to Bottom">&#9660; Bottom &#9660;</a>
1

I've had the same issue. For me at one point in time the div's elements were not loaded entirely and the scrollTop property was initialized with the current value of scrollHeight, which was not the correct end value of scrollHeight.

My project is in Angular 8 and what I did was:

  1. I used viewchild in order to obtain the element in my .ts file.
  2. I've inherited the AfterViewChecked event and placed one line of code in there which states that the viewchild element has to take into the scrollTop value the value of scrollHeight (this.viewChildElement.nativeElement.scrollTop = this.viewChildElement.nativeElement.scrollHeight;)

The AfterViewChecked event fires a few times and it gets in the end the proper value from scrollHeight.

1

We can use ref and by getElementById for scrolling specific modal or page .

 const scrollToBottomModel = () => {
    const scrollingElement = document.getElementById("post-chat");
    scrollingElement.scrollTop = scrollingElement.scrollHeight;
  };

In the modal body you can call above function

 <Modal.Body
          className="show-grid"
          scrollable={true}
          style={{
            maxHeight: "calc(100vh - 210px)",
            overflowY: "auto",
            height: "590px",
          }}
          ref={input => scrollToBottomModel()}
          id="post-chat"
        >

will work this

1

A simple example with jquery

$('html, body').animate({
    scrollTop:   $(this).height(),
  });
1
  • hmm, does not work with huge <pre>'s in Google Chrome 100 :/ it just scrolls down to the start of the <pre>
    – hanshenrik
    Apr 22, 2022 at 9:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.