How To Use Custom Back To Top Button In Vue.js

Use Vue.js custom back to top button and it’s easily customizable also, without any npm plugin and without jquery.

Step 1: Components

<template>
    <div 
        @click="scrollToTop()" 
        :class="['back-to-top-btn', {'go-top': isTop}]"
    >
        <i class='ri-arrow-up-s-line'></i>
    </div>  
</template>

Step 2: JS

<script>
export default {
    name: 'BackToTop',
    data (){
        return {
            isTop: false
        }
    },
    methods: {
        scrollToTop() {
            window.scrollTo(behavior: ‘smooth’, 0, 0);
        },
    },
    mounted(){
        const that = this
        window.addEventListener('scroll', () => {
            let scrollPos = window.scrollY
            if(scrollPos >= 100){
                that.isTop = true
            } else {
                that.isTop = false
            }
        })
    }
}
</script>

Step 3: SCSS

<style lang="scss" scoped>
.back-to-top-btn {
    position: fixed;
    cursor: pointer;
    bottom: -100px;
    right: 20px;
    color: #ffffff;
    background-color: #FEB302;
    z-index: 4;
    width: 45px;
    text-align: center;
    height: 45px;
    opacity: 0;
    visibility: hidden;
    border-radius: 50%;
    font-size: 22px;
    transition: .6s;
    overflow: hidden;
    box-shadow: 0px 3px 10px rgba(0, 0, 0, 0.1);

    i {
        position: absolute;
        right: 0;
        left: 0;
        top: 45%;
        transform: translateY(-45%);
        text-align: center;
        font-size: 30px;
        margin-left: auto;
        margin-right: auto;
    }
    &.go-top {
        opacity: 1;
        visibility: visible;
        bottom: 50px;
    }
    &:hover {
        background-color: #FEB302;
        color: #ffffff;
        transition: .6s;
        box-shadow: 0 4px 6px rgba(50,50,93,.11), 0 1px 3px rgba(0,0,0,.08);
        transform: translateY(-5px);
    }
}
</style>

 

3 Comments:

  1. Nice tip, thanks!
    You can add use “window.scroll({ behavior: ‘smooth’, left: 0, top: 0 })” instead of “window.scrollTo(0, 0)” in order to add a smooth animation.

Leave a Reply

Your email address will not be published. Required fields are marked *