Vue scroll to top of element

Vue scroll to top of element
Photo by Becca Tapert on Unsplash

There are various ways to scroll to a bottom of a div with Vue.js

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

We can set the scrollTop property of a DOM element to its scrollHeight so that scroll it to the bottom.

Vue scroll to top of element
Photo by Mark Rasmuson on Unsplash

To start my weekend i have decided code a customizable scroll top component, component will be implemented with vue slots. Slots will allow us to passing any kind of html element to the component.

Component implementation

We will bind to scroll event and check Y axis scroll, this will allow us to hide/show compoment depending on the scroll of the page.

Next, we will make a function that scroll to top of the page step by step and make an simple animation.

Scroll top component

<template> @click="scrollTop" v-show="visible" class="bottom-right"> template> <script> export default { data () { return { visible: false } }, methods: { scrollTop: function () { this.intervalId = setInterval(() => { if (window.pageYOffset === 0) { clearInterval(this.intervalId) } window.scroll(0, window.pageYOffset - 50) }, 20) }, scrollListener: function (e) { this.visible = window.scrollY > 150 } }, mounted: function () { window.addEventListener('scroll', this.scrollListener) }, beforeDestroy: function () { window.removeEventListener('scroll', this.scrollListener) } } script> <style scoped> .bottom-right { position: fixed; bottom: 20px; right: 20px; cursor: pointer; } style>

Scroll top arrow

Now, with a generic component we will implement a new one: we will use font awesome icon and a simple css styles.

<template> class="btn btn-light"> :icon="['fas', 'angle-double-up']" size="3x" /> template> <script> import ScrollTopComponent from './ScrollTopComponent' export default { components: { ScrollTopComponent } } script> <style> .btn { border-radius: 8px; background-color: rgba(0, 0, 0, 0.55); padding-top: 27px; padding-left: 10px; padding-right: 10px; padding-bottom: 5px; } style>

Use

The component using is quite simple, we only need to place component on the DOM.

<template> class="container">

A super long component

template> <script> import ScrollTopArrow from '@/components/shared/blog/ScrollTopArrow' export default { components: { ScrollTopArrow } } script>

Result

Now when we are on top of the page component is hidden but when we scroll component shows up, you can see component ´s implementation on my github.

Vue scroll to top of element

References

Github
vue font awesome