Navigate to the Vuejs component's element that has a specified class name

When a component is loaded, I want it to automatically scroll down to display the element with a class name of 'actual-month' within an unordered list.

<b-card no-body header="<i class='fa fa-align-justify'></i> Unorderd List"  style="height: 680px">
          <b-tabs card pills>
              <b-tab v-for="debt in user_debts"  :title="Debts list"  :key="debt.id" class="card-height">             
                 <table class="table table-sm amortization-header header-fixed">
                  <thead>
                      <tr>
                        <th>Month</th>
                        <th>Balance</th>
                        <th>Paid</th>
                        <th>Debt</th>
                        <th>Nominal Interest</th>
                      </tr>
                  </thead>
                  <tbody> 
                    <tr v-for="month in amortization.schedule" :class="{'actual-month' : month.month == amortization.actual_month}">
                      <td>{{month.month}}</td>
                      <td>{{month.balance.toLocaleString()}}<span class="total">€</span></td>
                      <td>{{month.monthly_payment}}<span class="total">€</span></td>
                      <td>{{month.principle}}<span class="total">€</span></td>
                      <td>{{month.interest}}<span class="total">€</span></td>
                    </tr>
                  </tbody>
                </table>
              </b-tab>
          </b-tabs>
        </b-card>

Answer №1

To automatically scroll to a specific element on the page, you can utilize the scrollIntoView method:

mounted: function (){
  var targetElement = this.$el.getElementsByClassName("actual-month")[0];
  targetElement.scrollIntoView();
}

Answer №2

There are multiple approaches to achieve this task, but one effective method is to encapsulate it within a reusable mixin:

const scroller = {
  methods: {
    scrollToClass(className) {
      let el = this.$el.querySelector(className)
      let rect = el.getBoundingClientRect()
      window.scrollTo(rect.left, rect.top)
    }
  }
}

You can then utilize this mixin in the mounted hook, where this.$el is accessible:

new Vue({
  el: '#app',
  mixins: [scroller],
  mounted() {
    this.scrollToClass('.actual-date')
  }
})

For demonstration, check out this JSFiddle: https://jsfiddle.net/ha9hm9xe/

Answer №3

Expanding on Julien's response, in many scenarios, incorporating animated actions like instantly moving to a specific section of a webpage or employing smooth scrolling can greatly enhance the user experience:

element.scrollIntoView({ behavior: 'smooth' })

Answer №4

The solutions provided by others didn't quite resolve my issue - I kept encountering the error message:

cannot access property scrollIntoView of undefined
. To work around this problem, I found that adding a setTimeout did the trick.

Imagine you need to scroll to the first element with the class invalid after submitting a form:

const someComponent {
  ...
  methods: {
    validateForm() {
      if (formValid) {
        // submit form
        ...
      } else {
        // display errors
        ...
        // then scroll to the first one
        this.scrollToInvalidField();
      }
    },
    scrollToInvalidField() {
      // Adding this setTimeout prevents the "undefined" error from occurring.
      setTimeout(() => {
        let el = this.$el.getElementsByClassName('invalid')[0];
        el.scrollIntoView();
      }, 0);
    },
  },
  ...
}

Additionally, for a smoother scrolling experience, you can include { behavior: 'smooth' } as an argument in the scrollIntoView() function, as mentioned by @digout in their response.

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

Is there a way to transform a dynamically created JavaScript table into JSON or XML format and then store it as a file?

A dynamic table of properties is created in JavaScript using a function: // update table PropertyWindow.prototype._update = function (text) { if (text === void 0) { text = "&lt;no properties to display&gt;"; } this._propertyWindow.html(text); ...

Create a file object using content with the help of JavaScript

I am working with a file containing specific data const ics = 'BEGIN:VCALENDAR\n' + 'VERSION:2.0\n' + 'CALSCALE:GREGORIAN\n' + 'METHOD:PUBLISH\n' + 'END:VCALENDAR\n'; I am trying t ...

What is the solution for fixing the '$ not defined error' in a .js file with $ajax code?

var example = document.createElement("SCRIPT"); example.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"; var nodeScript= document.createTextNode("function test() {console.log('test message');$.ajax({ type: \"POST&bs ...

Verify the fonts that are functioning correctly

Despite using the "dancing script" Google webfont and adding it through @font-face, font-family, I am unable to see it in the browser. I would like to know how to determine which fonts are correctly uploaded and rendering properly while viewing a website ...

Retrieve information from the selected row within a table by pressing the Enter key

I have a search box that dynamically populates a table. I am using arrow keys to navigate through the rows in the table. When I press the enter key, I want to retrieve the data from the selected row. For example, in the code snippet below, I am trying to ...

React - while the get request successfully retrieves the desired object, the corresponding value is appearing as undefined when integrated into the React component

While working on a practice problem, I encountered a puzzling situation. When I console log the response body of my GET request, it shows that I am successfully fetching the correct object. However, when I log the object in the component where the GET requ ...

Unable to retrieve table header information when clicking on a table cell

My code is working perfectly, except for the fact that when I click on a cell, I cannot retrieve the table header text. Retrieving the row text works fine based on the code. If I use Object.keys(data) inside the alert function to retrieve the data, it give ...

Tips for transmitting HTML as a JSON object through the res.render function in expressjs

My issue involves a JavaScript function that returns an HTML element. I want to pass this element along for users to view as actual HTML, but it ends up appearing as a string with special characters like "<" and ">". For example, "<" appears as (& ...

Error: The addDoc() function in FireBase was encountered with invalid data, as it included an unsupported field value of undefined during the execution

As I attempt to input data into the firebase database, an error arises: 'FireBaseError: Function addDoc() called with invalid data. Unsupported field value: undefined'. The registration form requests 2 inputs - name and email. The function handle ...

Complex recurrent operation

Can anyone assist me in solving this complex loop? I need to call 5 API URLs, each a specific number of times before moving on to the next URL in sequence and then starting over again. https://www.example1.com should be called 4 times https://www.example2 ...

Transmit information from a Vue.js application to a Laravel application

I've started working on two separate projects - one using Vue.js (created with vue create project_name) and the other using Laravel (created with laravel new project_name). My goal now is to transfer data from the Vue.js project to the Laravel project ...

Unable to properly delete data in Express/Postgres

After developing a Kanban board using JavaScript without any frameworks on the front end, I integrated Express/Postgres on the back end. However, I am encountering an issue with the 'Delete' operation. While all other CRUD operations are functio ...

Extract information from JSON using a filter

Is there a way to extract the data value from the list without relying on index positions, considering that the order of arrays can change? I need to specifically target data where code === "size". Unfortunately, the existing structure cannot be ...

Animating elements in Nativescript Vue using v-show and transitions

I am facing some issues while using v-show with Nativescript. I attempted to create an animation as outlined in . When using v-show, the element doesn't completely disappear from the screen. Below is my code: <template> <Page actionBarHi ...

What is the best way to transfer a variable from an @Input property to a service within an Angular2 component?

I'm tackling what seems like a simple task, but I'm struggling to figure it out. My issue is this: How can I successfully pass a variable from @Input to a service in an Angular2 component? (Code has been simplified) This is my current component ...

Themeing for dark mode using styled components in Next JS

I have been searching for an answer to this question, but haven't found one yet Currently, I am using styled components with next js along with the use-dark-mode hook to manage theme changes and detection The global styles switch seems to work fine ...

AJAX File Upload: Sequentially Queuing Multiple Files

I am a beginner in the world of Javascript and jQuery. When I try to upload multiple files through a form, only the last file gets uploaded repeatedly. My goal is to upload each file one by one using AJAX requests asynchronously. Here's how I have ...

Tips for transferring data from a file located outside an Angular library to files within the Angular library

In the repository below, you will find a library named posts-lib. This library contains a file named posts.services.ts which is responsible for making http calls and retrieving a list of posts to display on the screen. Additionally, there is a component na ...

Injecting a full browser-screen DIV into the body of the webpage

Recently, I was tasked with developing a script that could be utilized on any website. As a test, I decided to use the Google search results page. My goal is simple - to have a full-screen semi-transparent div displayed on any site for cookie notification ...

Leveraging JQuery to extract the numerical value located between the slashes within a hyperlink

I need to extract numeric values from a link like this. For example: /produkt/114664/bergans-of-norway-airojohka-jakke-herre In this case, I want to fetch 114664. To achieve this, I have written the following jQuery code: jQuery(document).ready(functi ...