Rafael Augusto
Rafael Augusto

Reputation: 397

How scroll end page with vue js

How do I scroll to the bottom of the page?

scroll(){
    let container = this.$el.querySelector('#scrollingChat')
    container.scrollTop = container.scrollHeight
}

I'm doing this, and always calling my api answers, but it does not go to the bottom of the page

Upvotes: 6

Views: 21109

Answers (4)

Ohadsh
Ohadsh

Reputation: 46

You may take a look at Mozilla Docs as reference.

Code wise safest use with VueJS is, using nextTick() and ref attribution, especially if execution is triggered following an event (Example: Button Click). + works best if you use some VueJS framework.

Scroll can be applied with smooth behavior for a nicer UX.

Example for specific div

<template><div ref="myScrollTarget">...</div></template>
<script>
...
methods: {
  scrollToBottom() {
    const targetRef = this.$refs.myScrollTarget;
    this.$nextTick(() => {
      targetRef.scrollTo(
        {
          top: targetRef.scrollHeight,
          left: 0,
          behavior: "smooth"
        }
      );
    });
  }
}
...
</script>

Example for full page (window)

<template><div>...</div></template>
<script>
...
methods: {
  scrollToBottom() {
    this.$nextTick(() => {
      window.scrollTo(
        {
          top: document.body.scrollHeight,
          left: 0,
          behavior: "smooth"
        }
      );
    });
  }
}
...
</script>

Upvotes: 0

Mgasmi
Mgasmi

Reputation: 417

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

or you can use smooth scroll: https://github.com/alamcordeiro/vue-smooth-scroll

Upvotes: 2

a_lovelace
a_lovelace

Reputation: 510

If you create an anchor in your page like so:

<div id="top"></div>

you can use:

let elmnt = document.getElementById('top');
elmnt.scrollIntoView(false);

This page explains what the different alignment parameters do for scrollIntoView:

true - scrolls to top of element

false - scrolls to bottom of element

default it true

https://www.w3schools.com/jsref/met_element_scrollintoview.asp

Upvotes: 2

James Harrington
James Harrington

Reputation: 3226

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

This is will instantly scroll to the bottom of any page.

Upvotes: 12

Related Questions