Is it possible for Vue Router to remember the scroll position on a route and return to the same position when navigating back?

My Vue Router is not saving the scroll position and always loads at the top of the page (0, 0). Any suggestions on what could be causing this issue?

Here is my current router code setup:

const scrollBehavior = (to, from, savedPosition) => {
  if (savedPosition) {
    return savedPosition;
  } else {
    return { x: 0, y: 0 };
  }
};
const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  scrollBehavior,
});

Answer №1

Ensure to verify the support of history.pushState in the browser being tested. It is also important to log the savedPosition as no scrolling will take place if the values are falsy. When initializing the router instance, you have the option to provide the scrollBehavior function as shown below:

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
      return { x: 0, y: 0 }
  }
})

The scrollBehavior function takes in the to and from route objects. The third argument, savedPosition, is only accessible during a popstate navigation (activated by the browser's back/forward buttons).

This function can return a scroll position object either in the format:

{ x: number, y: number }
//or
{ selector: string, offset? : { x: number, y: number }} //offset only supported in 2.6.0+

If a falsy value or an empty object is returned, scrolling will not occur.

Please note that this functionality is dependent on the browser supporting history.pushState

If desired, you can save the current scroll offset before navigating. Here is a way to achieve it:

const container = document.querySelector('.container')
let scrollOffset = {x: container.scrollTop, y: container.scrollLeft}

Subsequently, store the scrollOffset prior to routing so that when the savedPosition is falsy, this object can be utilized.

Answer №2

  handleScrolling(to, from, savedPosition) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (to.hash) {
          return resolve({ selector: to.hash });
        } else if (savedPosition) {
          return resolve(savedPosition);
        } else {
          resolve(document.getElementById("root").scrollIntoView({ behavior: "smooth" }));
        }
      }, 1200);
    });

  },

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

Executable program contained within npm bundle

I am working on creating an npm package that can be executed as a command from the shell. I have a package.json { "name": "myapp", "version": "0.0.6", "dependencies": { "async": "", "watch": "", "node-promise": "", "rmdir": "", " ...

Problem with email verification process

Hey there, I'm currently working on validating an email address using regular expressions. Here is the code snippet I'm using: <input type="text" name="email" id="email"/> var email = $("input#email"), re = /^[A-Za-z ...

Is there a way to overlay a div on a particular line within a p element?

Within this paragraph lies a collection of text encapsulated by a < p > tag. When this content is displayed on the page, it spans across 5 lines. My objective is to creatively style and position a < div > tag in order to highlight a specific li ...

Change the value of input on onClick event in React

Although this may seem simple, it is a little confusing to me. I'm having trouble understanding why the input value in the following case is not being reset. handleReset() { this.setState({ data: "" }); } <button onClick={this.handleReset}>R ...

Switching the chosen option in the <select> element repeatedly

I have successfully set the selected value, but now I am wondering how to keep changing it continuously. Initially, my approach was to remove the "selected" attribute from all options and then add it back to the desired option. Surprisingly, this method w ...

Animate with ease upon mouse entry into the div

I have a question about hovering. $(".hover li img").mouseenter(function() { $(".overlay").animate({ left: pixels+"px" }); }); The overlay class is a transparent box around the image, with a red border. I want the border to move when hov ...

A step-by-step guide on accessing grouped column data in Angular UI Grid

How do we access the data of all rows within a grouped column in Angular UI Grid? For instance, when looking at the Grouping Tutorial, how can we retrieve all the company names from the 'Company' column? I have successfully obtained the aggrega ...

Disabling Navigation with Arrow Keys in Prettyphoto

Is there a way to prevent arrow keys from functioning in PrettyPhoto for a specific instance? I have tried using keyboard_shortcuts:false, but it still reloads the frame if left or right arrow keys are pressed, causing the form inside to reset. However, co ...

What is the best way to integrate the express-session logic with Prisma for optimal performance?

Hi there, I recently started using Prisma and want to integrate it with PostgreSQL. My main goal is to implement authentication in my backend, but I encountered issues while trying to create a session table. When working with raw SQL, I managed to add the ...

Sending POST Requests with Next.js Version 14

How can I send a POST request using axios in Next.js 14, I prefer axios but fetch is also okay. I have been getting an AxiosError: Network Error when I try to use axios and TypeError: fetch failed when using fetch. However, it works fine with Postman. I ...

Javascript is unable to locate the clientid

Encountering an error message like the following: 'System.Web.UI.WebControls.TextBox' doesn't have a definition for 'ClentID' and there isn't any extension method 'ClentID' that accepts the first argument of type &a ...

Repeatedly utilizing a drop-down menu

Can a <select> menu be written and utilized in multiple locations on a webpage? For instance: <select id="dm"> <option value="">Select Quantity</option> <option value="less ">50 - 60</option> <option value="me ...

The issue with Infinite Scrolling/Pagination feature in backbone.js persists

My goal is to implement an infinite scroll feature similar to Twitter using the Pagination plugin for backbone.js. Clicking the button/link #pagination a should load the next page of results from the backend and append it to the current view PhotoListView. ...

I'm looking to fill multiple input boxes with the same value

I am looking to pass the same value to multiple input boxes. Currently, the script below only displays in one box but I want to display the main box result in all multiple input boxes. <script type='text/javascript' src='http://code.jque ...

Unveiling the secrets of extracting element content using JavaScript (with JQuery) from an HTML object

I have written the code below to access the page "JQueryPage.aspx" and retrieve data from it using jQuery: <script type="text/javascript> $.get ( "JQueryPage.aspx", function(data) { alert("Data Loaded: " + data); ...

Creating multi-dimensional arrays using array lists with Axios and Vue.js

My knowledge of axios and JavaScript is limited, and I find myself struggling with creating a multi-dimensional array. 1. This is how I want my data to be structured : https://i.stack.imgur.com/kboNU.png userList: [ { ...

What strategies can be utilized to condense code when needing to adjust a className based on various props?

I am looking to condense this code, particularly the [if~else if] block, in order to dynamically change a className based on different props passed. export default function Button(props) { const { name, height, color, bgColor } = props; let className = ...

Raspberry Pi Fast Server: Issue with AJAX not locating images in directory and malfunctioning ID search

I'm completely new to Raspberry Pi, linux, and server concepts, so I'd appreciate explanations at a beginner level. My goal is to create a display similar to those you see in lobbies showing corporate slides and weather updates. While setting up ...

Simplest method for defining an associative array

Looking to create an array in the format shown below: [0: 0, 1: 1, 2: 2] This is achieved using the following code snippet: var arr = []; for(i=0; i<3; i++){ arr[i] = i; } Upon execution, my array appears as follows: [0, 1, 2] The values with ...

What is the best way to print a canvas element once it has been modified?

My goal is to include a "Print Content" button on a webpage that will print a canvas element displaying workout metrics. However, the canvas content, which consists of a visual graph of workout data, changes based on the selected workout (bench, squat, etc ...