Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { left:0, top:0 }. Is there a way to prevent this jump to the top during transitions triggered by the browser buttons, while still maintaining the behavior for other types of clicks, such as when using a router-link?

export const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition || to.query.page) {
            return savedPosition;
        } else {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve({ left: 0, top: 0 });
                }, 400);
            });
        }
    },
});

If anyone has a solution or suggestion, please let me know. Thank you!

Answer №1

To customize the behavior of scrolling, one can adjust the scrollBehavior function within the router configuration. This modification allows for checking whether the navigation of routes was initiated by utilizing browser navigation buttons (e.g., back and forward) or other methods like a router-link. By comparing the fullPath values of from and to, it is possible to determine if the router transition occurred due to the back or forward button.

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 it possible to iterate through HTML form data using JSON arrays or objects?

I've been searching this website and the internet for a while now, trying to figure out how to save multiple arrays to my localStorage. I asked a question earlier which helped me progress a bit, but I'm still struggling to grasp the concept. I c ...

Simplify your bootstrap Input field code by utilizing components or a similar method in Vue.js

Using a single file component with a pug template, I am faced with multiple input fields that have the same formatting. Here is an example: .input-group.input-group-sm .input-group-addon Purchase Price input.form-control(v-model='purchase_ ...

Display a smaller image preview in the product photo gallery

Hey there! I'm currently working on a website and looking to showcase my product in a similar way as shown here: I would like my main image to be displayed with all the other variants of the product image underneath, along with the same visual effect ...

Ways to prevent the execution of JavaScript code?

I have a website that contains a block where AJAX-loaded code is coming from a remote server. How can I prevent potentially harmful code from executing, especially when it originates from a remote source? Is using the "noscript" tag sufficient to protect a ...

I can't seem to figure out why I constantly struggle with adding a check mark to a checkbox using

Take a look at the code I've provided below : HTML : <input type="checkbox" name="xyz[1][]" id="sel_44" style="margin:2px;" value="12345" onclick="myClick(this)"> Javascript : <script> $('#sel_44').attr("checked", true); < ...

Obtain the data of the highlighted row in a telerik grid directly from the client side

I am attempting to retrieve the value of a GridBoundColumn with DataField="id" using JavaScript on the client side. When the user clicks on the image button within a row, I need to extract the id for that specific row and then invoke a web method by passin ...

Tips for implementing validation on dynamically inserted fields in a form

My form has two fields, and the submit button is disabled until those fields are filled with some text. However, if I add a third field dynamically using AngularJS, validation will not be supported for the new field. Check out the example here <butto ...

Getting the output from AJAX when the onreadystatechange event occurs

Struggling with retrieving a value from a function and storing it in a variable? Getting an "undefined" result due to JavaScript's asynchronous nature? Unsure how to fix this using "callbacks" or "promises"? Check out the code snippet below. The goal ...

What is the purpose of using *//<![CDATA[* and *//]]>* in a jQuery code snippet?

Check out this JavaScript code snippet that I have: <script type="text/javascript> //<![CDATA[ jQuery(document).ready(function() { jQuery("#page_template option[value='sidebar-page.php']").remove(); }); ...

Explore the capabilities of redux independent of the react framework

I've been searching for hours trying to find a way to access the store (to dispatch and observe) without using React Components, but have had no luck. Here's my situation. I created the store in the root of the App: import { Provider } from &ap ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

What is the best way to modify an Li element using the DOM in JavaScript?

Just the other day, I discovered how to use JavaScript and DOM to add and delete Li elements. Now I'm curious about how to edit those Li elements using DOM. Any suggestions? Thank you! ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

Bypass ESLint rule when using Uglify in the Vue build script like a pro!

Every time I try to execute npm run build, I encounter a consistent punc error in various lines. The issue seems to be related to the method in which I am defining functions within my components: <script> export default { data() {} } </scrip ...

When a custom throw is triggered in Vue, the console error message appears un

I have implemented a custom throw in the created() method of my component. throw new Error(`Cookie ${cookieName} not found.`); However, Vue logs this error into the console: [Vue warn]: Error in created hook: "Error: Cookie showLanguageInfo not found ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Combining Two Validation Methods for jQuery Validate Plugin

Seeking advice on how to incorporate custom validation methods from jQuery validate into another method for validating data. Specifically, I have a 'Document ID' field that can accept either CPF or CNPJ (Brazilian documents) and I need to validat ...

Incorporate a 404 Not Found redirect into the getServerSideProps method in Next.js

I'm seeking guidance on best practices for handling an HTTP 404 error in a server-side rendered page when the requested page lacks a corresponding server-side resource. For instance, let's say the requested page is http://localhost:3000/places/5 ...

Generating intricate JSON structures with JavaScript programming instructions

In the world of JSON, I am still a novice. I need to use JavaScript to construct the JSON structure below, but I'm struggling with adding the second element ("12101") and populating the people in the JSON Structure. Below is the code I tried, however, ...

The Vue Loader is unable to resolve images within third party CSS files located in the node modules directory

While using webpack to compile my vue.js application, I encountered an issue when importing a node_module css file that contained images. The images could not be resolved properly. <style lang="less"> @import '~@vue/vue'; </style> ...