0

I am making a chat app and what I want to archieve is when the dynamic messages are loaded in, that the page scrolls down with a smooth animation to the bottom of the div.

<ul id="messages">
                <li>
                    <p>Not logged in on Epic | Log in here: https://epic.clow.nl/login</p>
                </li>
            </ul>
Thomas Ponzo
  • 77
  • 1
  • 11
  • Does this answer your question? [Scroll to bottom of div?](https://stackoverflow.com/questions/270612/scroll-to-bottom-of-div) – johannchopin Dec 18 '19 at 20:00

3 Answers3

5

jQuery is not required for smooth scrolling. Try this -

window.scroll({
  top: 1000,
  behavior: 'smooth'
});

This will jump the webpage down 1000px.

Akshay
  • 530
  • 7
  • 20
  • I would increase the top to a much higher number, to make sure it goes all the way down – vsync Apr 26 '23 at 16:57
0

Okay second try now with native javascript.

There is this function.

window.scrollBy(0, 50);

This scrolls the windows down 50 every time its executed so you could maby make like a loop.

    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }

And do something like

function smoothToBottom() {
    // change the time to make the ani go faster or slower
    var scrollTimer = setInterval(scrollDown, 200);
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
        clearInterval(scrollTimer);
    }
}

function scrollDown() {
   window.scrollBy(0, 10);
}

I havent tested this but it could work.

-1

You could achieve this very easily with jquery. Just add this to your <head>:

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

And then add this to your javascript file:

function messagesAreLoaded() {
    $("div").animate({ scrollTop: $(document).height() }, "slow");
}

This function needs to be called when the messages are loaded. The <div> element then gets scrolled to the bottom. Just make the <div> element whatever element needs to be scrolled.

Hope this helps!