What is the reason behind window.scrollTo functioning as a cache for the scrollTo value

Currently, I am working on a project using Vue. On the user's homepage, there is a list of posts that are displayed. When the user clicks on "show full post," the list of posts is replaced by an expanded view of the single post.

However, a challenge arises when the user wants to go back to see the list of posts. The page automatically scrolls back to the top, regardless of where the user was previously scrolled to.

My goal is to have the page return to the exact point where the user was before clicking on "view full post."

To tackle this issue, I have implemented a solution where I store the current scroll position value when "show full post" is clicked. Then, when the user clicks on the back button, I use window.scrollTo to return to that position.

While this solution works the first time, it encounters issues in subsequent attempts as it always returns to the position of the first time.

I suspect that this problem may be related to Vue caching the function, but I am unsure of how to address it.

<template>
  <div>
    <post-list @showFullPost="showFullPost($event)" v-show="!showingFullPost"></post-list>
    <full-post @goBack="showAllPosts" v-if="showingFullPost"></full-post>
  </div>
</template>

<script> 
   export default{
     data: function(){
         return {
            currentHeight: 0,
            showingFullPost: false
         }
     },
     methods:{
       showFullPost(post){
          this.currentHeight = window.scrollY;

          //other code
       },
       showAllPosts(){
         //some code

         window.scrollTop(0, this.currentHeight); //this only works the first time and subsequently goes to the position of the first time
       }
     }
   }
</script>

Answer №1

After much trial and error, I finally stumbled upon a solution that worked.

Surprisingly, the issue was resolved by implementing a setTimeout function, although the reasoning behind it remains a mystery to me.

setTimeout(() => {
  window.scrollTo(0, this.currentHeight);
}, 20);

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

Enhanced JavaScript Autocompletion in Integrated Development Environments

What is the inner workings of Intellisense in IDEs like Webstorm and Eclipse for JavaScript? From which source do the suggestions originate? Is it possible to tweak the code to enhance the accuracy of the suggestions? https://i.sstatic.net/ZVBB3.png ...

Interfacing Contact Form Data from Vue Application to Magento Using API - A Step-by-Step Guide

Introduction A custom vue-component has been implemented on the application, serving as a contact form. This component is imported into the header component and enclosed within a modal container. The primary function of this contact form is to trigger an ...

Ways to split up array objects in an axios GET request

Hello, I recently implemented an AXIOS GET request that returns an array of objects. However, the current example I am using retrieves the entire array at once, and I need to separate the objects so that I can work with them individually. class CryptoAP ...

How can a Vue component be created with a template that solely consists of a property's text?

Looking for a way to incorporate plain text within a Vue component template area? The current method involves wrapping the text in a div, but this causes layout issues when concatenating components with other text fragments. This results in awkward spacing ...

VUE component disregarding CSS styles

Check out my awesome VUE component below: <template> <div> <div class="bottom-footer"> {{msg}} </div> </div> </template> <script> export default { ...

What is causing the Jquery repeater to not trigger .keyup and .change events on items beyond the second one?

I noticed that the .keyup and .change events are only triggered in the first input field and not after I add a new item. Is there a way to make these events trigger when adding a new field? http://jsfiddle.net/q8pcoaxf/ $('.field').on(& ...

Receiving a NULL value instead of the expected string in the soap request

My mobile application interacts with a SOAP web service using AJAX. The user is required to input their username and password in order to log in. When the login button is clicked, a JavaScript function is triggered to send the data to the web service via ...

HTML or JS/jQuery can create disorienting cursor behaviors

Is there a way to create a distorted or crooked mouse movement on a webpage, even though the user is moving the mouse normally? I'm exploring ways to simulate the experience of a Parkinson's or arthritic patient trying to navigate a web page wit ...

transferring information to d3.js

I have a json object structured in the following way { "tweet":[ {"text": "hello world"}, {"text": "hello world"} ] } When I check the console output of "data" in my code below, it shows me an Object tweet: Array[131]. However, when I l ...

Accessing location information using jQuery from Google's Geocoding API

Recently, I've been delving into the realm of Google Maps Geocoding and attempting to comprehend how to decipher the JSON data that it transmits back. This snippet showcases what Google's response looks like: { "results" : [ { ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the https://i.sstatic.net/ZX1AN.png Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem ...

ImageMapster for perfect alignment

I'm struggling with centering a div that contains an image using imagemapster. When I remove the JS code, the div centers perfectly fine, indicating that the issue lies with the image mapster implementation. It's a simple setup: <div class=" ...

What could be causing my select tags to appear incorrectly in Firefox and IE?

With the help of Jquery, my goal is to dynamically populate a select field when it is in focus, even if it already has a value. Once populated, I want to retain the previous value if it exists as an option in the newly populated field. Although this works ...

Creating a custom dialog box using JavaScript

How can I create a customized dialog box in the center without displaying "the host name says..." using CSS? function myFunction() { alert("Record Save"); } Thank you in advance! ...

Create a dynamic JavaScript animation with frames

Is there a simpler method to animate a sprite with just 4 frames in HTML Canvas? Having a background in AS3 and C#, I found the code below to be overly complicated. It seems like I'll be spending hours trying to decipher it. Is there a more modern or ...

Prevent a specific item from being included in an Electron list using JavaScript

When extracting filenames from a directory, this code is currently being used: getFilenameList = () => { let select = document.getElementById("filenameSelect"); let options = []; fs.readdirSync(folderUrl).forEach(file => { options.pus ...

Currently, I am a beginner in the world of reactjs and I have embarked on a practice project to expand my knowledge of the platform. I am in need of assistance in creating a feature that

fetch("https://sampleapi.com/api/v1/employees").then( response => { response.json().then( result => { console.log(result.data); if (result.data.length > 0) { var content = ""; re ...

What is the best way to differentiate between words enclosed in quotation marks using colors?

Working on my shop, I've added a section for "Colors available", but now I want to color different words with different colors using Javascript, CSS, or HTML. <button onclick="getColors()">Colors Available</button> <script> ...

Web Page Content Scrambling/Character Exchange

I've encountered a perplexing issue that seems to strike randomly, yet I've managed to replicate the problem on three different desktops. Oddly enough, some other desktops never experience this issue and I'm at a loss as to what could be cau ...

Display HTML content within a Material-UI Card component using React

Currently, I am utilizing the < CardHeader /> component nested within a < Card />. <CardHeader title={card.title} subheader={`${moment(card.createdAt).startOf('minute').fromNow()}` + ' by ' + <div>ABC</div>}/ ...