Determine whether the user has scrolled past a specific threshold

Is there a way to display the button with the id backtotop only when the user has scrolled more than 250 pixels?

This is my code:

<template>
    <div>
        <button v-if="checkScroll" class="goTop" @click="backToTop">
            <i class="fa fa-angle-up" aria-hidden="true"></i>
        </button>
    </div>
</template>

<script>
    export default {
        methods: {
            computed: {
                checkScroll() {
                   if ($(document).scrollTop() > 250) {
                       return true;
                   } else {
                       return false;
                   }
               }
           },
           backToTop() {
              this.$scrollTo('html');
           },
        }
    }
</script>

I've implemented the code above but it's not working as expected. The button remains hidden even when I scroll beyond 250 pixels and I'm not getting any errors.

Answer №1

Don't forget to remove the event listener:

new Vue({
  el: "#app",
  data() {
    return {
      scroll: null
    }
  },
  methods: {
    handleScroll(e) {
      this.scroll = window.scrollY || window.scrollTop
    }
  },
  created() {
    window.addEventListener('scroll', this.handleScroll);
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll);
  }
})
html {
  height: 3000px; /* a random height for demonstration */
}

button {
  position: fixed;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe888b9bbeccd0c8d0cc">[email protected]</a>/dist/vue.js"></script>

<!-- scroll and button behavior -->

<div id="app">
  <button v-show="scroll > 250">foobar</button>
</div>

Answer №2

Implement the onScroll event using Javascript to track user scrolling, allowing you to utilize scrollTop() to seamlessly navigate to the top of the page upon button click.

Ensure that the positioning is set to fixed.

For further details, refer to these resources: onScroll scrollTop()


To toggle the visibility of the button, manipulate its size directly via HTML DOM methods. For instance:

document.getElementsByClassName("goTop")[0].width = 30;

Answer №3

Looking for some cool sketches and features? Check out codepen.io They have a variety of in-demand features available for free! If you need a scroll to top functionality, here's a page you can customize to suit your needs https://codepen.io/rolandtoth/pen/eMamVK

.scrolltop-wrap {
$size: 3rem;
$offsetBottom: 2rem;
$offsetHorizontal: 2rem;
$scrollToRevealDistance: 12rem; // scroll offset to reveal scroll-to-top link

Instead of javascript, this uses all scss. If you need help converting scss to css, try this generator out

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

What could be causing the function to not work properly within the React component?

Having trouble with a React component utilizing speech recognition for converting speech to text. Initialized the recognition functions within the component but encountering errors. Need assistance in troubleshooting this issue. const speechRecognition = w ...

Issue encountered in v-on event handler: "authentication is not a valid function" - Vue.js

I am currently incorporating Firebase into a VueJS project. My API credentials are stored in a file named fb.js import firebase from 'firebase' var firebaseConfig = { apiKey: "*****", authDomain: "*****", proje ...

What is the process for including an SVG file in my JavaScript .textContent?

I've been struggling to add an exclamation SVG to this section, but for some reason I can't make it work. I've searched on Google for a solution, but haven't found one yet. The SVG file is already downloaded and stored in my project fo ...

Unable to access property within JSON object sent via POST request

I encountered an issue TypeError: Cannot read property &#39;tasks&#39; of undefined While attempting a new POST request on my API, here is the request body I am using: { "name": "example1", "description": "teaching example1", "rules" ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

How to use jQuery to remove the last element from an array when the back button

Currently encountering an issue with removing the last element from an array when a back button is clicked. The console is displaying the correct elements in the array, but it seems that the array.slice function is not working as expected, and I'm str ...

Tips for validating Vue Bootstrap Typeahead with Vee Validate

Currently, I am utilizing vue js 2.6.11 along with vue-bootstrap-typeahead 0.2.6 and vee-validate 3.3.7. Below is my component that includes a typehead: <template> <vue-bootstrap-typeahead :value="keyword" :data="data&quo ...

"Troubleshooting an issue with post requests in VueJS and Laravel resulting in

Trying to execute a basic POST request using VueJS 2 (with axios) and Laravel 5.3, but encountering an issue where my method consistently returns an empty array when attempting to print $request->all(). The blade template includes the following meta ta ...

A guide on successfully handling errors while utilizing S3.getsignedurlpromise() in node.js

I am faced with a challenge in my project involving a node.js server that downloads images from an s3 bucket and serves them to a React client. The issue arises when the wrong file key is sent to the S3 client, as I want to handle this error gracefully by ...

Utilizing AngularJS: Techniques for Binding Data from Dynamic URLs

Just starting out with AngularJS We are using REST APIs to access our data /shop/2/mum This URL returns JSON which can be bound like so: function ec2controller($scope, $http){ $http.get("/shop/2/mum") .success(function(data){ ...

Working with HTML5 Canvas to Clip Images

Is there a way to implement a tileset image in canvas like this one? I am trying to figure out how to make it so that clicking on the first tile returns 0, clicking on the tenth tile returns 9, and so on... Any suggestions on how to clip a tileset on an ...

Creating a connection to an external website through a JavaScript function within an Angular application

I am currently working on an Angular application. Within the index.html file, there is a header that contains links to external websites. <a href="#" onclick="getExternalUrl('about.html');">Click here </a> <scr ...

Top method for creating integration tests in React using Redux and Enzyme

Currently, I am working on setting up integration tests within my application. There are a few API calls that occur both when the component mounts and upon a button click. The response from these API calls is stored in the app's store, which then upd ...

The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercas ...

Utilizing Repurposed Three.js Shapes

I have been experimenting with Three.js to visualize the path of a particle in a random walk. However, I encountered an issue where geometries cannot be dynamically resized so I had to come up with a workaround by removing the existing line from the scene, ...