What is the best way to implement a scroll to top/bottom button globally in Vue?

I have created a scroll-to-top and scroll-to-bottom button for my application. However, I want to make these buttons accessible globally throughout the app without having to repeat the code in every page where the component is needed. Currently, I am including hasScroll:false,

hasVerticalScroll(){this.hasScroll=document.body.offsetHeight > window.innerHeight};
, declare
<v-app v-scroll="hasVerticalScroll">
, and
 <ScrollToTop v-if="hasScroll"/>
in each page that requires this functionality. Is there a more efficient way to simplify this process?

Default.vue

<script>

export default {
    name: "DefaultLayout",
    data() {
        return {

            hasScroll: false
        };
    },
    methods: {
        hasVerticalScroll() {
          this.hasScroll = document.body.offsetHeight > window.innerHeight;
    }
  },
watch: {
  '$route' (to, from) {
    this.hasVerticalScroll()
  }
}
}
</script>

<template>
  <v-app dark v-scroll="hasVerticalScroll">

    <ScrollToTop v-if="hasScroll"/>
  </v-app>
</template>

ScrollToTop.vue

<template>
      <div v-scroll="onScroll" >
        <v-btn v-if = "!isVisible"
             fab fixed bottom right color="primary" @click="toBottom" >
            <v-icon>mdi-arrow-down-bold-box-outline</v-icon>
        </v-btn>

        <v-btn v-else
            fab fixed bottom right color="primary" @click="toTop">
            <v-icon>mdi-arrow-up-bold-box-outline</v-icon>
        </v-btn>
      </div>
</template>

<script>

export default{
    data () {
        return {
        isVisible: false,
        position: 0,
    }
  },
   methods: {
    onScroll () {
      this.isVisible = window.pageYOffset> 50
    },
    toTop () {
      this.position = window.pageYOffset
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth'
      })
    },
    toBottom(){
      let pos = this.position > 0 ? this.position : document.body.scrollHeight
      window.scrollTo({
        top: document.body.scrollHeight,
        behavior: 'smooth'
      })
    },
  }
}

Answer №1

If my understanding is correct, you will need to implement a global event listener in ScrollToTop.vue without utilizing vuetify's v-scroll directive.

Here is an example of how this can be achieved:

        mounted() {
            this.listener = () => {
                this.isVisible = window.pageYOffset > 50;
            };

            document.addEventListener('scroll', this.listener);
        },
        beforeUnmount() {
            document.removeEventListener('scroll', this.listener);
        },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem arising from reduxjs/toolkit - unable to execute action dispatch

As I delve into learning React, focusing on reactjs/toolkit in this specific section, I am working through a series of basic examples to enhance my understanding. One particular example involves simulating a user logging into their account. Despite identif ...

Having trouble loading background color or image in three.js

I've been struggling to load a background image or color on my webpage. Despite trying various methods, including commenting out javascript files and checking the stylesheet link, nothing seems to work. Even when I load the three.js scene with javascr ...

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

How can you use plain javascript to drag and drop the cross sign within the box in the grid?

Creating a grid in HTML where clicking on a box will draw an x sign and remove it if clicked again. View the DEMO here. Challenge Description:- I am now looking to implement dragging the cross (x) sign to another grid within the box, but cancelling the ...

Experiencing code coverage challenges in Angular 8 relating to function properties

https://i.sstatic.net/WQpVB.png Looking for suggestions on how to create a unit test case in Jasmine to address the code coverage problem. Any ideas? ...

Having issues with AJAX and button submit while trying to upload a file using Flask

I've been attempting to incorporate a file upload feature (specifically a .csv file) using bootstrap, and then submit it by clicking on a button. I've experimented with various methods to implement the file upload functionality, but haven't ...

Using AngularJS to update text content retrieved from a file and display it in a textarea

Is there a way to create a textarea using AngularJS that can be populated either by typing, entering a URL, or uploading a plain text file? While I am able to load the file content into the variable linked to the textarea, I'm facing an issue where ge ...

Tips for transferring a dataTable from C# code behind to jQuery

I am trying to pass a string as a table of data from C# code behind to jQuery using two functions: C# [System.Web.Services.WebMethod(EnableSession = true)] public static List<ListItem> GetImageArray(string AccNo) { string result = string.Empty; ...

Embracing async-await while awaiting events in node.js

I am attempting to incorporate async await into a project that is event-driven, but encountering an error. The specific error message I am receiving is: tmpFile = await readFileAsync('tmp.png'); ^^^^^^^^^^^^^ SyntaxError: Unexpec ...

Tips for closing print window dialog during Protractor testing

Currently, I am performing end-to-end testing using protractor. During a specific test, I need to verify if the print button is successfully creating a PDF. When the test clicks on the button, it triggers a print window dialog as shown below: https://i.st ...

Extract information from a string to retrieve the array specifications

After making a request to the server, I received the following response: { "statusCode": 200, "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F10645774 ...

Having trouble getting images to display in Vue markdown?

I am currently utilizing the vue-markdown package for rendering markdown content. The package works fine except for images, which do not display as expected. Interestingly, when using an img element with the correct file path, the image shows up without an ...

Tips for making a hide and reveal FAQ section

Currently working on creating a FAQ page for my website, I ran into a challenge. My goal is to have a setup where clicking on a question will reveal the answer while hiding any previously open answers. So far, I have managed to achieve this functionality p ...

Once the PostgreSQL container is stopped with docker-compose down, the previously used port becomes unavailable for use again

Currently, I am involved in a project which utilizes express as the server and postgres as the database to delve into dockerization. The server relies on the database being operational. Initially, when running docker-compose up everything functions correct ...

Exploring Angular 9: Harnessing the Power of Fork Join with an Array of

I have a challenge where I need to send multiple API requests to an endpoint by iterating over an array of values To handle this, I decided to use rxjs library and specifically the forkJoin method //array to keep observables propOb: Observable<any>[ ...

What is the best way to incorporate multiple functions within a React button?

I need to implement a functionality where the startClick function is triggered on BackButton click before executing the dispatch (giveForm2PreviousStep(props.currentStep, props.goToStep)) method. How can this be achieved? Inquiry JS const Inquiry = props ...

Callbacks for AJAX responses that are asynchronous

After using AJAX in a limited and straightforward manner for some time, I find myself currently debugging a web application that heavily relies on JavaScript and JQuery for client-side coding. One issue that has caught my attention is the possibility of mu ...

Adjust the width of a textarea dynamically as you type by detecting keyup events

Two text areas have the same text formatting. Their IDs are textareaA and textareaB. I've successfully added functionality to resize textareaA on keyup. How can I make textareaB resize its WIDTH while the user is typing in textareaA? Here's wha ...

Display <div> exclusively when in @media print mode or when the user presses Ctrl+P

Looking for a way to create an HTML division using the div element that is only visible when the print function is used (Ctrl+P) and not visible in the regular page view. Unfortunately, I attempted the following method without success. Any advice or solut ...

Chrome hanging after AJAX delete operation has been executed

After conducting a same-origin AJAX delete using jQuery, any subsequent calls made by the same client to the server are getting stuck. The specific issue is outlined below. Can you please review and let me know if there's something incorrect, as this ...