How can I make a div scroll by a precise number of pixels using Vue?

In my Vue2 app, I attempted to scroll up a div by 10px using the following method:

this.$refs.hello.scrollTo({ top: 10, left: 0, behavior: "smooth"});

Unfortunately, instead of scrolling up by 10px, it scrolls all the way to the top. How can I scroll to a specific height?

Check out this example on CodeSandbox: https://codesandbox.io/s/youthful-blackwell-wl5x6?file=/src/components/HelloWorld.vue:531-630

Answer №1

One effective approach is to scroll to the current scrollHeight of the reference element once the list has been updated.

Example

new Vue({
  el: '#app',
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      list: [],
    };
  },
  mounted() {
    let i = 0;
    for (i = 0; i < 19; i++) {
      this.list.push(i);
    }
  },
  methods: {
    addItem() {
      this.list.push(0);
      setTimeout(() => {
        const targetTop = this.$refs.hello.scrollHeight;
        this.$refs.hello.scrollTo({
          top: targetTop,
          left: 0,
          behavior: "smooth",
        });
      })
    },
  }
})
.hello {
  overflow-y: auto;
  height: 200px;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
<div id="app">
  <div class="hello" ref="hello">
    <h1>{{ msg }}</h1>
    <div v-for="item in list" :key="item">
      <div style="margin-bottom: 20px">{{ item }}</div>
    </div>
    <button @click="addItem">add</button>
  </div>
</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

Debugging Vue with Jest

I am currently troubleshooting my Vue project in VS Code, which uses Jest for testing. Jest Configuration: module.exports = { moduleFileExtensions: [ 'js', 'jsx', 'json', 'vue' ], transform: { ...

Every checkbox on the Angular 6 platform has been chosen

In my model class named processAnexOne.ts, I have the following structure: export class ProcessAnexOne { documentList: string; } Within the component class, I have initialized an instance as follows: export class ProcessAnexOneComponent implements O ...

The function URL.createObjectURL() is not recognized in Nuxt

Hey everyone, currently I'm utilizing Nuxt I have an image saved on the server as a blob that I want to display on the client side This is how my Component is structured: <template> <div class="product-page"> <div clas ...

Dealing with unresolved promises in async/await functions

What is the best approach for handling unresolved promises? For instance: class Utils { static async thisFunctionOnlyResolvesWhenPassed2AndNeverRejects(number: number) { return new Promise((resolve, reject) => { if(number === 2 ...

Issues with AngularJS dirty validation for radio buttons not being resolved

I have encountered an issue with my form fields. The validation for the email field is working correctly, but the radio button field is not displaying any errors when it should. I am using angular-1.0.8.min.js and I cannot figure out why this is happenin ...

Modifying the content of JSON key values

In my application, I am using MongoDB, Express, and MongoDB. When receiving data on the server side, it comes in the form of an array of objects (JSON) named upProbations. For example, let's say I find information about Max: [ { Name ...

"Ways to retrieve an array of dates within a specified range of date and time

I am working with date fields in my project { tripScheduleStartDate: '2018-12-05T18:30:00.000Z', tripScheduleEndDate: '2018-12-07T18:30:00.000Z', } Is there a way to generate a datetime array from the start date to the end date, lik ...

Utilizing a Json.Net object within an Ajax request

Is there a way to pass a .Net object in an Ajax call using the Json.Net javascript library instead of json2.js? You can find more information on passing complex types via Ajax calls at this link: I am familiar with how to serialize and deserialize object ...

What is the correct location to store the bower.json file?

I'm currently using bower 1.2.2 to handle my client-side libraries for the first time with a new node app. I'm unsure whether I should initialize bower in the main project root alongside gruntfile.js and package.json, or within the static directo ...

What are the limitations of using a JS file within an Angular application?

I am struggling to integrate some js methods from a file into an angular application. Unfortunately, the browser is unable to recognize the js file. I have tried following the guidelines in this SO post, but the browser still cannot locate the file in the ...

JavaScript inheritance through prototypes and the properties of objects

I am currently exploring the concept of prototyped inheritance in JavaScript for a function. This process is well documented in Wikipedia's javascript article. It functions smoothly when dealing with simple JavaScript types: function Person() { t ...

Adding new elements to a list with Jquery, seamlessly integrating them without the need to

I am facing a bit of a roadblock in figuring out how to achieve this, mainly due to my limited understanding of JavaScript. The code that I have been looking at is as follows: http://jsfiddle.net/spadez/VrGau/ What I am attempting to accomplish is allowi ...

No feedback received from JSON

Hi, I'm having trouble receiving JSON response using JavaScript. My goal is to display the JSON data as a treeview. index.html: <!DOCTYPE html> <html> <head> <title>JSON VIEW</title> <link href="https:// ...

Using angularjs to include content from other files is known as

As I delve into the concept of creating directives in AngularJS, I am faced with the imminent end of Angular 1.x and the rise of Angular 2.x. The shift seems daunting, but I am determined to bridge this gap seamlessly. In my quest for clarity, I stumbled ...

How to modify values in a JSON array using JavaScript

Currently, I am facing an issue with displaying dates properly on the x-axis of a graph created using Highcharts. To solve this problem, I need to parse the dates from the JSON response. Despite my attempts to manipulate the JSON date, I have not been able ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

Variable type linked to interface content type

Is it possible to link two fields of an interface together? I have the following interface: export interface IContractKpi { type: 'shipmentVolumes' | 'transitTime' | 'invoices'; visible: boolean; content: IKpiContent; } ...

Execute the script using ajax

Is it possible to execute JavaScript within an AJAX request? I attempted to include some JavaScript code in the PHP file that was called by an AJAX command. The purpose of this script was to modify an HTML attribute on the parent page. However, it did not ...

Accessing a subcollection with DocumentSnapshot in Firebase using JS9

Just had a quick question. Is anyone familiar with how to achieve something similar using Firebase JavaScript v9? Essentially, I have a `userDoc` that is a DocumentSnapshot and I need to access a sub-collection with the document snapshot. Here's the c ...

Tips for adjusting the placeholder color in Material UI using React JS

Is there a way to customize the background color and flashing color of the Skeleton component in Material UI? I would like to implement custom styling for it, similar to what is shown below: <Skeleton variant="circle" classes={{root:'pla ...