Tips for maintaining the browser scroll bar at the top when switching routes in AngularJS

How can I ensure that the scrollbar is always at the top when a user is redirected to a different page after scrolling down on the home page? The autoscroll feature in the code below doesn't seem to be working. Any suggestions would be greatly appreciated. Thank you.

index.html


   <!DOCTYPE html>
    <html ng-app="riskAssessmentApp">
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
            <meta name="viewport" content="width=device-width">

            <title>Risk Assessment</title>

            <link rel="icon" type="image/x-icon" href="favicon.ico">

            <!-- bootstrap.css contains normalize, so it needs to go first  -->
            <!-- build:css(.tmp) styles/main.css -->
            <link rel="stylesheet" href="bower_components/orcit-theme/dist/styles/bootstrap.css">
            <link rel="stylesheet" href="bower_components/orcit-theme/dist/styles/kendo.bootstrap.css">
            <link rel="stylesheet" href="bower_components/orcit-theme/dist/styles/kendo.common-bootstrap.css">
            <link rel="stylesheet" href="bower_components/orcit-theme/dist/styles/orcit.css">
            <link rel="stylesheet" href="bower_components/bac-multiselect/bacMultiselect.css">
            <link rel="stylesheet" href="styles/site.css">
            <link rel="stylesheet" href="styles/bootstrap-override.css">
            <link rel="stylesheet" href="styles/kendo-override.css">
            <link rel="stylesheet" href="styleNew/multiselect-treeview.css">
            <link rel="stylesheet" href="styleNew/main.css">
            <link rel="stylesheet" href="styles/style.css">
            <!-- endbuild -->
        </head>
        <body>
            <div ui-view autoscroll="false"></div>

            <!-- build:js scripts/scripts.js -->
            <script src="bower_components/orcit-bower/src/jquery/dist/jquery.js"></script>
            <script src="bower_components/orcit-bower/src/angular/angular.js"></script>
            <script src="bower_components/orcit-bower/src/angular-cookies/angular-cookies.js"></script>
            <script src="bower_components/orcit-bower/src/angular-off-click/offClick.js"></script>
            <script src="bower_components/orcit-bower/src/angular-resource/angular-resource.js"></script>
            <script src="bower_components/orcit-bower/src/spin.js/spin.js"></script>
            <script src="bower_components/orcit-bower/src/angular-spinner/angular-spinner.js"></script>
            <script src="bower_components/orcit-bower/src/angular-ui-bootstrap/src/accordion/accordion.js"></script>
            <script src="bower_components/orcit-bower/src/angular-ui-bootstrap/src/bindHtml/bindHtml.js"></script>
            <script src="bower_components/orcit-bower/src/angular-ui-bootstrap/src/collapse/collapse.js"></script>
            <script src="bower_components/orcit-bower/src/angular-ui-bootstrap/src/modal/modal.js"></script>
            <script src="bower_components/orcit-bower/src/angular-ui-bootstrap/src/position/position.js"></script>
            <script src="bower_components/orcit-bower/src/angular-ui-bootstrap/src/tooltip/tooltip.js"></script>
            <script src="bower_components/orcit-bower/src/angular-ui-bootstrap/src/transition/transition.js"></script>
            <script src="bower_components/orcit-bower/src/angular-ui-router/angular-ui-router.js"></script>

            <script src="bower_components/orcit-bower/src/angular/angular.min.js"></script>
            <script src="bower_components/orcit-bower/src/kendo/js/kendo.web.min.js"></script>
            <script src="bower_components/orcit-bower/src/kendo/js/kendo.all.min.js"></script>


            <script src="bower_components/bac-multiselect/bacMultiselect.js"></script>
            <script src="bower_components/kendo-multiselect-treeview/kendo-multiselect-treeview.js"></script>
    </body>
    </html>

scroll.js

angular.module('riskAssessmentApp').run(function($rootScope, $anchorScroll) {
    /* Scroll to the top of the page after successfully changing routes */
    $rootScope.$on('$routeChangeSuccess', function() {
        $anchorScroll();
    });
});

Answer №1

If you want to automatically scroll to the top of the page whenever the route changes, you can utilize the $anchorScroll function in AngularJS.

angular.module('YOUR_APP')
    .run(function($rootScope, $anchorScroll) {
        /* Scroll to the top of the page after a successful route change */
        $rootScope.$on('$routeChangeSuccess', function() {
            $anchorScroll();
        });
    })
    .config(function($uiViewScrollProvider) {
        $uiViewScrollProvider.useAnchorScroll();
    });

Answer №2

The following code snippet helped me fix my problem:

angular.module('Your-App').run(function($rootScope,$window) {
      /* scroll to the top of the page after the route successfully changes */
    $rootScope.$on('$viewContentLoaded', 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

AngularJs stops the link from being clicked more than once

I am utilizing AngularJS for specific features in my system, not to build a single-page application. I am struggling to determine why Angular is preventing the page from refreshing after navigating there or how to disable/find a workaround. Here is an exa ...

Utilizing a MONGO_URL to efficiently run multiple Meteor applications on a single server

I have successfully deployed a Meteor application on my Ubuntu server using Meteor Up (MUP) and everything is working well. However, when attempting to deploy a second app on the same server, I encounter issues with connecting to MongoDB. The error message ...

Get the nearest offspring of the guardian

I have a main 'container' div with multiple subsections. Each subsection contains 1 or 2 sub-subsections. Let's say I have a variable that holds one of the subsections, specifically the 4th subsection. This is the structure:container > s ...

Fan Animation in CSS

I have three unique images that I would like to animate in a fan-like manner consecutively. I prefer not to merge the images in Photoshop, as I want them to be displayed one after the other. Here is the code snippet (dummy images are used): .bannerimg ...

Issue with resetting the state of a react-select component remains unresolved

I'm currently facing two issues with my react-select component: Firstly, once I select an option, I am unable to change it afterwards. Second, when my form is reset, the react-select component does not reset along with the other fields. For simplici ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

Having trouble with the jQuery slideUp function?

Exploring some jQuery features for a trial run, I stumbled upon an unusual behavior. Perhaps someone in this forum can provide some insight. Keep in mind that this is all just test code, so please overlook any messy aspects. Currently, I am working with ...

Ways to stop touch events on every element but one through JavaScript

One issue I encountered was preventing scrolling in the background while a popover is open. For desktop, it's simple with CSS: body { overflow: hidden; } The problem arose on IOS where this rule didn't work as expected and the background could ...

Returning to the previous page is done by navigating back using the previous URL in Next.js

Recently, I encountered a situation where I had implemented filters on a webpage. Upon applying the filters, the URL of the page would change and additional query strings would be appended to the end. This caused an issue when navigating back using the b ...

What is the best way to automatically add a date and timestamp to every new entry?

I am currently working on a project that utilizes AngularJS and Ionic frameworks. The main feature of the project will involve users inputting data to create a list, and allowing any user to comment on each item in the list. One challenge I have encounter ...

The issue of ng-checked not functioning correctly in conjunction with ng-change and ng-model

There is a checkbox that should only be checked if a certain property is false. The HTML code for this checkbox is as follows: <input type="checkbox" ng-model="list.IsProject" ng-checked="list.IsProject==false" name="IsProject" id="IsProject" ng-chang ...

Using Vuex in the router: A comprehensive guide

I am having trouble accessing data from the store in the router. I have attempted three different methods, but none of them seem to be working correctly. Here are the methods I tried: // ReferenceError: store is not defined console.log(store.state); // ...

Ways to display URL parameters on an HTML page without using PHP

I'm currently working on a website using HTML (without PHP) and I'm facing an issue with displaying URL parameters on an appointment confirmation page. The appointment details are being successfully passed through the URL parameters, but I'm ...

I encountered an error while using the router: TypeError: Cannot read property 'use' of undefined

Hello everyone, I am new to node.js and seeking help from experts. I am currently working on a code for user synchronization using node.js + AWS Cognito + Facebook Login. I followed an example from this link. Everything was going smoothly until I reached ...

The chatbot text input feature is malfunctioning and failing to display the entered text in the chatbox

Hi there! I'm in the process of creating a chatbot using a basic input text box and button in HTML, with a php start function. Unfortunately, when I enter text into the textbox, nothing is showing up on the screen and the button doesn't seem to b ...

Using websockets in a React client application

Attempting to establish a connection with a backend layer running on localhost, here is the provided source code: const { createServer } = require("http"); const cors = require("cors"); const photos = require("./photos"); const app = require("express")( ...

Issue with saving objects using $cookies.putObject in Angular 1.4

Recently, I made the transition from angular version 1.2 to 1.3 and then to 1.4 which deprecated $cookieStore in favor of $cookies. Even after adding the line $cookies.putObject('user', user);, the data is not being saved to cookies (I confirmed ...

Looking to locate the child div elements within a parent div

I am having trouble determining the individual lengths of child divs within parent classes that share the same name. For example: <div class="main-div"> <div class="parent"> <div class="child"></div> <div class= ...

Update the second dropdown menu depending on the selection made in the first dropdown menu

While I know this question has been posed previously, I'm struggling to apply it to my current situation. In my MySQL database, I have a table named "subject" that includes columns for subject name and subject level. Here's an example: Subject ...

What strategies can I use to optimize the code for the function provided?

This function allows for the dynamic display of select tags for location selection based on employee designation. The current code functions correctly, but I believe it can be optimized further. // Function to activate different location options based on e ...