Using Vue js to scrollIntoView will only affect the specific element's div

I am currently working on a Vue page that consists of two divs. The Select-Div contains a list of elements, and when I click on an element from the list, the Scroll-Div is supposed to scroll to the corresponding ID element inside it. Ideally, the scrolling should position the element in the center of the Scroll-Div, where detailed information about the selected list element is displayed.

The issue I'm facing is that when I use scrollIntoView, the entire page scrolls to the center as well. This causes both the Scroll-Div and the main page to move, which is not the desired behavior.

It's important to note that the Scroll-Div includes a recursive component, so I am restricted to using IDs instead of refs.

Here is my goTo() function defined on the main page:

    goTo(id) {
      const element = document.getElementById(`Id-${id}`);

      if (element) {
         element.scrollIntoView({
           block: "center",
           behavior: "smooth",
         });
      }
    },

This function receives the emitted ID from the Select-Div and scrolls to the corresponding HTML ID within the Scroll-Div.

https://i.sstatic.net/D1LED.png

Answer №1

Using the scrollBy API can be a helpful solution for this task.

For more information, you can visit: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy

Here's an example of implementing this in a Vue 2 component:

<template>
  <div class="select-component">
    <div class="container">
      <div class="scroll-div" ref="scrollDiv">
        <p id="a">A lorem ipsum</p>
        <p id="b">B lorem ipsum</p>
        <p id="c">C lorem ipsum</p>
      </div>

      <div class="select-div">
        <button @click="goto('a')">Goto a</button>
        <button @click="goto('b')">Goto b</button>
        <button @click="goto('c')">Goto c</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    goto(id) {
      let scrollDiv = this.$refs.scrollDiv;
      let el = scrollDiv.querySelector(`#${id}`);

      if (el) {
        let scrollDivRect = scrollDiv.getBoundingClientRect();
        let idRect = el.getBoundingClientRect();

        let y = scrollDivRect.y;
        let y1 = idRect.y;

        let offset = y1 - y;

        scrollDiv.scrollBy({
          top: offset,
          behavior: "smooth",
        });
      }
    },
  },
};
</script>

You can see a demo of this implementation here:

https://codesandbox.io/s/vue-scroll-to-item-on-click-for-scrollable-container-9s7xi?file=/src/components/SelectComponent.vue

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

How do server side cookies and javascript cookies interact with each other?

Can you explain the connection between the cookies generated by the Cookie Class in Servlet and document.cookie in JavaScript? ...

Implement a callback function to dynamically generate variables and display them within an HTML element

Apologies in advance for any errors I may make as I am a beginner when it comes to javascript, jquery, and json. I have a script that retrieves data from a json file and displays it on a webpage using javascript, jquery, ajax (I believe), and json. When ...

Vuetify's paginated server-side datatable does not support client-side sorting

The Challenge The issue I am facing revolves around using a server-side paginated datatable. Specifically, when utilizing the Vuetify data tables component and attempting to perform client-side sorting due to using a public API that I did not develop, the ...

Utilizing React, generate buttons on the fly that trigger the display of their respective

Looking for a way to dynamically display 3 buttons, each of which opens a different modal? I'm struggling to figure out how to properly link the buttons to their respective modals. Here's the code I've attempted so far: Button - Modal Code: ...

Utilize variable as both a function and an instance of a class

Is there a way to access a variable as both a function and an object instance using TypeScript? log("something"); log.info("something"); I've attempted various methods, such as modifying the prototype, but nothing has proven succ ...

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

What are the common issues that arise when creating a library with Vue CLI?

After setting up the application, I followed the official documentation to start building the library without any modifications: https://cli.vuejs.org/guide/build-targets.html#app npm run build --target lib --name myLib 'src/components/HelloWorld.vue ...

Feeling uncertain about Node, NPM, Bower, and how to set them up for Bootstrap?

Looking to expand my knowledge in web development, I have a solid understanding of HTML, JS, CSS, and server-side programming. However, the concepts of Nodejs, npm, and Bower are still unclear to me. In order to begin a new project, I created a designated ...

Retrieving data in [slug].js using Reactjs

I am currently working on a project in Reactjs utilizing the "nextjs" framework. I have successfully managed to retrieve data (specific blog details) based on the slug([slug.js]). However, I now need to display data from all other blogs within the same c ...

Having trouble getting my HTML file and CSS styles to render properly in Chrome

Currently, I am in the process of developing a website and facing challenges with displaying CSS properties accurately. Despite seeking input from friends and users, my HTML file is not rendering as expected within various browsers such as Chrome, Edge, an ...

I received no response when I checked my Discord messages

I'm currently working on creating a bot that will send a daily morning message at 9 o'clock with a customizable reaction. Right now, it's successfully sending the message on Discord but there seems to be an issue with the reaction part. Can ...

Encounter an issue during npm installation of electron: "Error verifying the initial certificate."

I recently developed a new app directory and ran the command npm init. However, I encountered an issue while trying to install Electron with the following line of code: npm install electron --save-dev. The error message I received is as follows: > [em ...

Steering clear of inserting 'Array' into a database through autocomplete using Js, Ajax, and Json

I'm currently working on a script that auto-populates input fields based on the autocomplete feature of the first input field. Although the script works fine and everything looks good when I hit submit, the problem arises when I check the database. A ...

When the child element's "aria-expanded" attribute is set to true, a CSS class should be dynamically

Is there a way to apply a grey background to the first div when the dropdown is open? I've managed to add CSS based on the child elements' aria-expanding attribute, but I'm unsure how to do it for a parent element. Since I am using Vue, I pr ...

Triggering AWS Lambda functions with SQS

Utilizing AWS and SES for sending emails and SMS through a Lambda function using NodeJs. I need to make more than 1k or 500 REST API calls, with the average call taking 3 seconds to execute a single lambda function request. It is essential to process mul ...

In ReactJS, when passing an array of objects to a child component, the first instance may sometimes return as undefined, causing the code to break

Currently, I am in the process of creating a personal blog for my brand. The "Posts" section is designed to retrieve data from a basic JSON via an API. At present, I have used mirageJS to mock the API and employed the useEffect and useState hooks to set th ...

Why is receiving input value in React not successful?

Attempted to retrieve input value when user clicks search, but encountered difficulties. var Login = React.createClass({ getInitialState: function () { return {name: ''}; }, handleSearch(){ alert(this.state.name); // Why isn't ...

Displaying a hand cursor on a bar chart when hovered over in c3.js

When using pie charts in c3js, a hand cursor (pointer) is displayed by default when hovering over a pie slice. I am looking to achieve the same behavior for each bar in a bar chart. How can this be done? I attempted the CSS below, but it resulted in the h ...

Issue with React / Express failing to route links accurately

Currently, my React project is functioning well except for Express. I have been struggling to find comprehensive tutorials on implementing correct routing with Express in a MERN stack application. I have come across some Stack Overflow posts, but none of ...

Leveraging AngularJS $promise in conjunction with NgResource

As I delve into the world of AngularJS, I have encountered promises which have proven to be quite beneficial in my learning journey so far. Now, I am eager to explore the optional library resource.js in AngularJS. However, I stumbled upon examples that lef ...