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.

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

What is the best way to execute synchronous calls in React.js?

Currently, I am a novice in working with React JS and I have been tasked with implementing a feature to reset table data in one of our UI projects. Here is the current functionality: There is a save button that saves all overrides (changes made to the or ...

Mastering asynchronous function handling in Node.js

I'm currently experiencing an issue with printing two statements using two functions var mongoose = require( 'mongoose' ); var_show_test = mongoose.model( 'test' ); exports.showTest = function(req,res) { var jsonString = []; ...

Unraveling exceptions in Node.js akin to handling them in Java

I'm seeking to develop a node application and I need guidance on exception handling. In Java, we utilize the exception class for this purpose. How can I achieve something similar in node? Are there any libraries available specifically for handling exc ...

Is there a way to filter out only the objects from the JSON data and exclude the strings?

I am facing an issue while looping through a JSON object. The presence of strings in the JSON is causing the loop to fail. How can I iterate only through the objects in the JSON without affecting the loop? My main goal is to iterate through the objects co ...

The filter is displaying incorrect categories

I am facing an issue with creating a work filter based on the last column which represents categories. When I select an option from the dropdown, I want to display only that specific category and hide the others. Currently, when I try clicking on an option ...

Tips for navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

"Learn the trick to concealing a modal and unveiling a different one with the power of jquery

Whenever I try to open a modal, then click on a div within the modal in order to close it and open another one, I encounter an issue. The problem is that upon closing the first modal and attempting to display the second one, only the background of the seco ...

Struggling to implement .indexOf() in conjunction with .filter()

Hello, I'm new to JavaScript and ES6. Currently, I am working on a react-native app that utilizes Firebase and Redux. One of my action creators acts as a search bar function to fetch data from Firebase. Here's the code I have so far: export cons ...

Learning about the functions Promise.all and Array.map()

My current project involves retrieving data from multiple APIs and aggregating them into a final array that will be displayed in the UI using React. Let me explain the scenario. First, I retrieve the main data from the primary API: const response = await ...

Protractor can now successfully locate and interact with a nested button element

I am trying to click on the second button, but I can't differentiate between the two buttons using class names. div class="ng-view ff-domain ng-scope"> <div class="hero-unit blur-background ng-scope"> <h1></h1> <h2> ...

Tips on handling a redirection request following a fetch post request

When communicating with my node server (Express) using fetch to build a Single Page Application (SPA), I have encountered an issue. Upon each request to the server, I validate the session and redirect to a login page if it is not valid. However, I noticed ...

How to create select options in Angular.js without using the ng-option directive

I receive a JSON object from a service and I am using some of its fields to populate my select option list. However, when I try to print the selected value in my controller, the output response is "undefined". Can someone help me figure out what I'm ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...

Can JQuery be used to detect text input in real-time in a textarea field?

Currently, I have a button for "post" that becomes active when text is typed into the text area. The issue arises when all text is deleted from the text area, as the button remains active in its coloured state despite being disabled using the following cod ...

Adding ngChange programmatically in Angular without using attributes is a common challenge faced

I am attempting to replicate the functionality of the ng-change attribute within a directive without making changes to the HTML (thus excluding the use of the ng-change property). After examining the Angular source code for the ngChange directive, I have ...

Setting up a Webpack configuration for packaging a Vue component as an npm module

Below is the primary JavaScript code for my component: import './sass/main.scss' import Vlider from './Vlider.vue' function install(Vue) { if (install.installed) return; install.installed = true; Vue.component('vlider ...

Navbar active class not updating on jQuery page scroll

My one-page website has a fixed navbar that I want to change its active status when scrolling down to specific div positions. Even though I tried using jQuery, the code doesn't seem to work as intended. Here is the snippet: // SMOOTH SCROLLING PAGES ...

Troubleshooting the Vue.js component rendering issue

I am trying to display only one object from the data on firebase using [objectNumber]. I want to show {{ligler[1].name}} in the template, but it is causing errors: Error when rendering component Uncaught TypeError: Cannot read property 'name' o ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

Steps for aligning the upper rectangular text in the center of the larger rectangular border

https://i.stack.imgur.com/7yr5V.png I was aware of a particular element in html that had text positioned in the upper left corner, but my knowledge didn't go beyond that. Should I be adjusting the translation on both the X and Y axes based on the par ...