When you press the back button and navigate to a different page, the scroll position will remain unchanged

I'm facing an issue with scrolling on my angularjs app.

Currently, the app consists of 2 pages: The first page displays a list of customers, where you can select one to view their details. The second page is a list of companies, following a similar selection process.

To navigate between these pages, I am using a panel along with $location.path(). Additionally, there is a back button implemented using $window.history.back().

The problem arises when selecting an item from either the customers or companies list and then pressing the back button - the app returns to the previous page while maintaining the scroll position. This behavior occurs without any custom implementations, solely relying on $window.history.back().

However, the issue happens when transitioning to another page (without scrolling) after using the back button - the scroll position remains unchanged. Yet, simply scrolling even slightly will reset the position. Furthermore, if the back button isn't used, everything functions as expected.

Therefore, the main concern is determining how to reset the scroll position when moving to another page post the use of $window.history.back().

It's worth noting that I have incorporated the infinite-scroll plugin, although disabling it did not impact the situation, leading me to believe the plugin itself is not the cause of the problem.

Answer №1

A while back, I encountered a similar issue and devised a simple workaround (although not the most elegant one).

My solution involved storing the wrapper's scrolltop value in the scope when the view changed, and then reapplying that value when navigating back.

I can't quite recall how it behaved when using the browser's back button, so you might want to test that out.


If you're interested, here's the code snippet for changing the view and storing the scrollTop value: https://github.com/jedrzejchalubek/Reed/blob/master/src/app/controller/all.js#L20

angular.extend($scope.view, {
    panel: false,
    section: 'single',
    single: el,
    scrollPosition: $('#thumbs').scrollTop()
});

And here's how to go back and reapply the scrollTop value: https://github.com/jedrzejchalubek/Reed/blob/master/src/app/directives/back-to-list.js#L14

scope.$apply(function() {
    scope.view.section = 'list';
    scope.view.panel = false;
});
$('#thumbs').scrollTop(scope.view.scrollPosition);

You can find the project on Github if you want to take a closer look and see if it helps: https://github.com/jedrzejchalubek/Reed

Answer №2

To capture reload events, simply trigger functions within the initialization of your controller. Make sure these controllers are enclosed in an Immediately Invoked Function Expression. Here's how it can be done:

(function() {

 angular.module("pstat")
         .controller("homeCtrl", homeCtrl);

  homeCtrl.$inject = ['$log', 'dataService', 'localStorageService', '$http'];
  function homeCtrl ($log, dataService, localStorageService, $http) {
    var vm = this;
    $(document).getElementById("yourId").scrollTop(0);

  });
})()

By implementing this approach, the page will reset to a vertical scroll offset of 0 when the controller is initialized, such as when navigating back to this page using $window.history.back event.

Answer №3

After making some modifications to the well-known phonecatApp based on the AngularJS tutorial, I successfully implemented the following feature:

    phonecatApp.run(function($rootScope, $window) {
        $rootScope.$on('$viewContentLoaded', function(){
            $(document).ready(function(){ window.scrollTo(0, 0); });
        });
    });

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

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

Omit any items from an array that do not have any child elements

Upon receiving data from the server in the format of a flat tree, I proceed to transfer this data to the JsTree library for tree building. Before sending the data to JsTree, I filter out any empty elements of type "folder" that do not have children. Below ...

Navigating horizontally within a list using Sencha Touch2

I currently have a list set up with the following configuration: var grid = Ext.create('Ext.List', { scrollable: { direction: 'horizontal', directionLock: true }, store: compStore, i ...

Getting the length of child elements in Angular using ngFor loop

Can anyone help me figure out how to check the length of a child element in my Angular *ngFor loop? I am fetching data from a real-time firebase database. What am I doing wrong? Here is the code snippet I am using: <div *ngFor="let event of events"> ...

The Nodejs express static directory is failing to serve certain files

Hello everyone, I'm currently working on a project using NodeJs, Express, and AngularJS. I've encountered an issue where my page is unable to locate certain JavaScript and CSS files in the public static folder, resulting in a 404 error. Strangely ...

What is the best way to assign a unique color to each circle?

Struggling to assign random colors to each circle in my canvas. Currently, they all have the same color that changes upon refresh. I'm aiming for unique colors on each circle but my attempts have been unsuccessful so far. Check out my code below: v ...

Refresh needed for Material UI styles to load correctly in Next JS

UPDATE: Reproducible issue https://github.com/ganavol409/next-material-ui-classes-bug Issue seems to be related to Higher Order Components and importing useStyles from Material UI Implemented Solution: https://github.com/mui-org/material-ui/blob/master/ ...

What is the best way to display an image in HTML?

I have successfully created an autocomplete search box that retrieves product names, but I am struggling to display the product photos. Here is the code snippet I am using: <asp:TextBox ID="txtContactsSearch" runat="server" Width="261"></asp:Text ...

Insert half a million records into a database table using JavaScript seamlessly without causing the webpage to crash

I am facing an issue with my report system where running a single report query results in over 500,000 rows being returned. The process of retrieving the data via AJAX takes some time, but the real problem arises when the browser freezes while adding the H ...

Fascinating CSS rendering glitch observed on zooming in: all browsers create a noticeable gap between containers except for Firefox

I'm experiencing a rather intriguing and peculiar issue with css styles when zooming in and out on the browser. Specifically, I've created a material ui card where the background-color changes upon clicking with an animation effect. The animati ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...

When making an AJAX request to an ASP.NET web method, strange characters are appended to the end of the response text. This issue seems

I need assistance with the following code: $.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', url: location, data: JSON.stringify(ajaxData), dataType: 'xml', success: ca ...

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

Store the output of a MySQL query as a variable in JavaScript code

As I work on developing a discord bot, one area that I am focusing on involves implementing a database for certain functions. My current challenge revolves around creating a command that retrieves the names of all tables stored in the database. While I hav ...

press a cURL PHP ajax button to trigger an action

Hello everyone, I could really use some help here. I've been looking at similar questions but none of the answers seem to apply to my situation. I extracted a page using curl, however, there's a button on that page that I am unable to interact w ...

AngularJS has encountered an issue with a route resolve promise that has not been completely resolved

I'm currently working on a simple task to manage user roles within routes. The goal is straightforward: Verify the role of the logged-in user on each route (using a resolve function to authenticate the user based on token or login credentials) Direc ...

Utilize multiple $rootScope.$on functions for increased event handling

Looking to run a specific portion of code only when two $broadcast events occur? Here's what I have: In controller1: $rootScope.$broadcast('receivedData'); In controller2: $rootScope.$broadcast('dataLoaded'); Current code snip ...

'Error: Object does not have access to the specified property or method 'values'

I've been working on writing some code to retrieve and read a JSON file. It seems to work fine in Chrome, but I'm running into issues with IE11, which is the browser I need to use. I've tried changing variable names, but the problem persists ...

The command 'ng' is not a valid internal or external command, and it cannot be run as an operable program or batch file on the Mean Stack platform

Hey there, I'm in the process of developing a meanstack application. Every time I try to run 'ng new client' command, it gives me an error saying 'ng' is not recognized as an internal or external command, operable program or batch ...

Tips for implementing multiple selectors in YUI

Is there a way to use multiple selectors in YUI (YUI 2) similar to jQuery? $('h1, h2, el1, el2, .content, .title').css('color', 'red'); How can I achieve the same in YUI without having to individually add classes using YAHOO ...