Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to bottom of div with Vue.js

I have a Vue component with several elements in it. I want to automatically scroll to the bottom of that element when a method in the component is called (basically, do the same as in Scroll to bottom of div?). However, I haven't found the way to get the element within my component and modify scrolTop

I'm currently using Vue 2.0.8

like image 816
angrykoala Avatar asked Nov 21 '16 21:11

angrykoala


People also ask

How do I scroll to a specific element in Vue?

We can scroll to an element with Vue. js by assigning a ref to the element we want to scroll to. Then we can scroll to the element by calling the scrollIntoView method on the element assigned to the ref. We have the scroll to last button that calls scrollToElement .

How do I scroll in Vue?

A vue directive to make a scrollable element scroll by draging to the scroll direction.


2 Answers

As I understood, the desired effect you want is to scroll to the end of a list (or scrollable div) when something happens (e.g.: a item is added to the list). If so, you can scroll to the end of a container element (or even the page it self) using only pure Javascript and the VueJS selectors.

var container = this.$el.querySelector("#container"); container.scrollTop = container.scrollHeight; 

I've provided a working example in this fiddle: https://jsfiddle.net/my54bhwn

Every time a item is added to the list, the list is scrolled to the end to show the new item.

Hope this help you.

like image 80
Italo Ayres Avatar answered Oct 14 '22 13:10

Italo Ayres


2022 easy, readable, smooth scrolling ability, & won't hurt your brain... use el.scrollIntoView()

scrollIntoView() has options you can pass it like scrollIntoView({behavior: 'smooth'}) to get smooth scrolling out of the box and does not require any external libraries.

Here is a fiddle.

methods: {   scrollToElement() {     const el = this.$refs.scrollToMe;      if (el) {       // Use el.scrollIntoView() to instantly scroll to the element       el.scrollIntoView({behavior: 'smooth'});     }   } } 

Then if you wanted to scroll to this element on page load you could call this method like this:

mounted() {   this.scrollToElement(); } 

Else if you wanted to scroll to it on a button click or some other action you could call it the same way:

<button @click="scrollToElement">scroll to me</button> 

The scroll works all the way down to IE 8. The smooth scroll effect does not work out of the box in IE or Safari. If needed there is a polyfill available for this here as @mostafaznv mentioned in the comments.

like image 43
maxshuty Avatar answered Oct 14 '22 13:10

maxshuty