Menu Close

How to scroll to bottom of div with Vue.js?

Sometimes, we want to scroll to bottom of div with Vue.js.

In this article, we’ll look at how to scroll to bottom of div with Vue.js.

How to scroll to bottom of div with Vue.js?

To scroll to bottom of div with Vue.js, we assign a ref to the element we want to scroll to and call scrollIntoView on the ref.

For instance, we write

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

    <div ref="scrollToMe">
      <!-- content -->
    </div>
  </div>
</template>

<script>
export default {
  //...
  methods: {
    scrollToElement() {
      const el = this.$refs.scrollToMe;

      if (el) {
        el.scrollIntoView({ behavior: "smooth" });
      }
    },
  },
  //...
};
</script>

to define the scrollToElement method that gets the div with the scrollToMe ref.

Then we call el.scrollIntoView if el isn’t null.

We call it with { behavior: "smooth" } to make the scrolling smooth.

And we set the click handler of the button to scrollToElement to do the scrolling on click.

Conclusion

To scroll to bottom of div with Vue.js, we assign a ref to the element we want to scroll to and call scrollIntoView on the ref.

Posted in vue