Tips for adding a scroll-to-top button on a page with only a vertical scroll bar

How can I make the scroll to top/bottom button only show up on pages with a vertical scrollbar? Currently, the button is not appearing when the page contains a vertical scrollbar. Any suggestions on how to implement this feature?

ScrollToTopBottom.vue

<template>
      <div v-if= "hasVerticalScroll" 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.scrollY > 500
    },
    toTop () {
      this.position = window.scrollY
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth'
      })
    },
    toBottom(){
      let pos = this.position > 0 ? this.position : document.body.scrollHeight
      window.scrollTo({
        top: pos,
        behavior: 'smooth'
      })
    },
  },
  computed: {
      hasVerticalScroll(){
        console.log('offsetHeight',document.body.offsetHeight);
        console.log('windowinner',window.innerHeight);
        return document.body.offsetHeight > window.innerHeight;
      }
    }
}

</script> 

Answer №1

To optimize your code, you can refactor the hasVerticalScroll function to be a method within the parent component and listen for scroll events:

Vue.component('scrollToTopButton', {
  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>
  `,
  data () {
    return {
      isVisible: false,
      position: 0
    }
  },
   methods: {
    onScroll() {
      this.isVisible = window.scrollY > 50
    },
    toTop() {
      this.position = window.scrollY
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth'
      })
    },
    toBottom(){
      let pos = this.position > 0 ? this.position : document.body.scrollHeight
      window.scrollTo({
        top: pos,
        behavior: 'smooth'
      })
    },
  },

})
new Vue({
  el: "#demo",
  vuetify: new Vuetify(),
  data() {
    return {
      hasScroll: false
    }
  },
  methods: {
    hasVerticalScroll() {
      this.hasScroll = document.body.offsetHeight > window.innerHeight; 
    }
  }
})
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f5939a9b81b5c3db8d">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f7818292839e918eb7c5d98f">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec9a9989acdec294">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98f8c9c8d909f80b9cbd781">[email protected]</a>/dist/vuetify.js"></script>
<div id="demo" >
  <v-app v-scroll="hasVerticalScroll">
    <v-main>
      <v-container >
        <div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div>
        <div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div>
        <scroll-to-top-button v-if="hasScroll" ></scroll-to-top-button>
      </v-container>
    </v-main>
  </v-app>
</div>

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

Verify the ability to view a webpage

I am currently working on creating a method to check if data access is equal to next.data.access. Since it's an array, I cannot use the includes method. It would be enough for just one of the data access values in the array to return true. auth.guard ...

Having an issue while running the command "npm start" in Visual Studio with React.js

PS C:\Users\PC1\Downloads\portfolio_website-STARTER> npm start > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d0d120f091b12111412220a181f0e140918500e091c0f09180f3d4c534d534d">[email protect ...

How should a value be correctly retrieved from a separate function?

Let's say there is a function: function name(){ var first_name = "mike"; } The goal is to pass the value of first_name to another function. One way to do this is: function name(){ var first_name = "mike"; getName(first_name); } But what if y ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

Trouble arises when attempting to incorporate the Restangular dependency with Angular using browserify

I've been using browserify to manage my angular dependencies successfully, however, when I try to add restangular I encounter an error: "Uncaught Error [$injector:modulerr]". Here's a glimpse of my package.json: "browser": { "angular": "./ ...

Why would you need multiple root handlers?

One interesting feature to note is that multiple callback functions can be used as middleware to handle a request. These callbacks can take on different forms - they could be in the form of a single function, an array of functions, or even a combination of ...

Learn the best way to send query parameters through the Next.js navigation router and take advantage of

Currently, I am implementing import { useHistory } from 'react-router-dom' const history = useHistory() ... history.push('/foo?bar=10') However, only the 'foo' part is being pushed into the url. What is the correct way to pas ...

Encountering a JSON_PARSER_ERROR when trying to call Google FCM using MobileFirstAdapter JS

I am working on integrating Google FCM Api for sending Push Notifications. Below is the snippet of code from my JavaScript file: function sendNotificationToUser() { var request={ path :'/fcm/send', method: 'POST&ap ...

Is it possible to change the inner html to null during an active ajax request?

My goal is to have two separate data.html files inserted into two different HTML files without needing a click event. I want the structure of my data.html files to remain consistent, while allowing the template of my website to change dynamically by callin ...

What is the best way to personalize Material UI elements, such as getting rid of the blue outline on the Select component?

Embarking on my journey of developing a React app, I made the decision to incorporate Material UI for its array of pre-built components. However, delving into the customization of these components and their styles has proven to be quite challenging for me ...

Node.js causing issues with retrieving data from REST Calls

I am trying to make a REST API call from my PHP and Node.js application to a specific URL provided by the client, which is expected to return a JSON object. While I am able to successfully retrieve data using PHP, I'm encountering issues with my Node ...

How should .has(), .get() and .set() be properly implemented for a JavaScript Map() within an ExpressJS server?

Feeling thrown off by javascript Map()? My query revolves around javascript Map() - the set, get, and has() functions. Despite thinking I was an expert, it seems I still have things to learn... Situation: I'm dealing with a 'global' map sto ...

The table appears to be fixed in place and will not scroll, even though the data

Previously, my code was functioning perfectly with the mCustomScrollbar I implemented to scroll both vertically and horizontally on my table. However, while revising my jQuery code for organization purposes, I seem to have unknowingly altered something tha ...

Encountering an error when attempting to upload a file to S3 using JS Vue

I'm attempting to upload a file to my S3 bucket using the aws-s3 library, but I am encountering this error in the console: https://i.stack.imgur.com/lk47U.png Here is the code for the component: <template> <input type="file" @ch ...

Incorporate a jQuery userscript on Firefox that includes a link to a form

Attempting to incorporate a search link into an online form using a userscript with jQuery, specifically for Firefox. I typically work in Chrome, so I'm encountering some challenges with compatibility in Firefox. However, I need this to be functional ...

How to incorporate Mixin in your Nuxt template

I'm having trouble utilizing the mixin function in my template. Although Vue documentation states that mixins and components are merged, I am unable to call the function. getImage is not a function Mixin export default { data() { return { ...

Tips for displaying axios status on a designated button using a spinner

Utilizing a v-for loop to showcase a list of products retrieved from an API request. Within the product card, there are three buttons, one for adding items to the cart with a shopping-cart icon. I aim for the shopping-cart icon to transform into a spinner ...

What is the best way to append something to the textContent property of an HTML tag within a markup page?

While working on resolving an XSS vulnerability in the jqxGrid where the cell content is rendered as HTML, I encountered a scenario like this: <a href="javascript:alert('test');">Hello</a>. To address this issue, I am exploring ways t ...

How can we enable SOAJS to operate on NodeJS versions higher than 0.12?

Currently, We were required to revert our NodeJS platform back to version 0.12 in order for our SOAjs dashboard to function properly. What changes need to be made in our SOAjs implementation to support the latest NodeJS versions? Thank you ...

The registration feature powered by JQuery is experiencing technical difficulties and not functioning

Having trouble with a registration system on my website at *. When someone registers, it should either show an error message or display "true" if the registration is successful. I have a javascript file (http://pastebin.com/mv9CWZcT) set up to redirect the ...