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
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 .
A vue directive to make a scrollable element scroll by draging to the scroll direction.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With