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

Leveraging Material-UI: Utilize props in useStyles method while employing Array.map()

After delving into the world of passing props to makeStyles in Material-UI, I stumbled upon this insightful answer. The solution presented involves passing props as a variable, which is quite useful. However, my aspiration is to extend this functionality t ...

Saving resources with a promise in Angular

I am facing a challenge while trying to handle a promise from the angular $resource save function. According to the documentation, I should be able to access the raw $http promise by using the $promise property on the returned object. Here is an example: ...

The content within the iframe is not displayed

I've set up a dropdown menu with separate iframes for each option. Here's the code I used: $(function(){ $('#klanten-lijst').on('change',function(){ $('#klanten div').hide(); $('.klant-'+t ...

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...

Tips for eliminating repetitive code in JavaScript

I have a jQuery function that deals with elements containing a prefix 'receive' in their class or ID names. Now, I need to duplicate this function for elements with the prefix 'send'. Currently, it looks like this: function onSelectAddr ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

The mapDispatchToProps function is failing to work, throwing an error: Uncaught TypeError: _this.props.addCountdown is not a function

Currently, I am facing an issue while working on my first app. The problem arises with a form component that should send an object via an onSubmit handler. onSubmit = (e) => { e.preventDefault(); this.props.onSubmit({ title: ...

The input object parameter for the Web API Delete method is found to be lacking,

My WebAPI asp.net mvc controller Delete method is receiving a null object called contact, and despite thorough code checks, I can't identify the root cause. Interestingly, my edit operation works flawlessly in a similar manner. What could be causing ...

Discovering WebElements nested within other WebElements using WebdriverJS

Looking at this HTML structure <div> <div> <p class="my-element"></p> </div> <div> <div> <div> <p class="the-text"> I want to retrieve this text</p> </div> </div> <div> ...

I am attempting to transfer information from one page to another in Next.js, but unfortunately, I am experiencing difficulties in

Encountering the following error message: "Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead." Any assistance will be greatly appreciated. export default func ...

Every time I hover, my jQuery code keeps repeating the hover effect

I am currently facing an issue that has me stumped on finding a solution. The problem arises when I hover over the .div multiple times, the animation just doesn't stop and keeps running continuously. What I aim for is to have the .hidden element fad ...

How can I pass my cookie token in a Next.js server-side component request?

My Next.js version is 14.1.0 and I am currently using the App router. async function Page() { const dataPromise: Promise<any> = getData(); const data = await dataPromise; console.log('data: ', data); return ( .... ); } The ge ...

Activate the text area message by clicking on the href link

I am currently working on customizing the intercom plugin for a WordPress site. My goal is to have a message triggered when a user clicks on a hyperlink, essentially simulating the enter key press in a textarea. Here is the code snippet that I am using: ...

Verify if an Ajax request has been made

I've been trying to figure out how to determine if a request is made via AJAX in C#, but I'm having trouble getting it to work. Below is the code I'm using. I am using a method to make an AJAX call on the client side (I'm using the Acti ...

Retrieve all form data using the ng-click directive in AngularJS

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script> <div ng-app="myApp"> <div class="container" ng-controller="CtrlList"> <div class="row"> <div ng-repeat="x ...

The error of "Uncaught ReferenceError" is being triggered by the use of `process?.env?

A bug was discovered in our front-end code related to the following snippet: <span style={{ color: 'red' }}>{process?.env?.REACT_APP_HEADER_SUFFIX ?? ''}</span> The bug triggered the following error message: Uncaught Refere ...

Using React refs to target multiple elements dynamically with the help of the map

My code effectively catches when the dropdown is clicked outside, and it's working well: displayOptions() { return _.map(this.props.selections, (option, index) => { return ( <div className="ui icon top dropdown" ...

Responsive Design: Concealing a Sidebar with CSS

Seeking assistance with optimizing the layout of my app, . It currently displays a menu on the left and a login form in the center, with a graph shown to users upon logging in. Is there a way to configure it so that when accessed on iOS: 1) the left menu ...

Click to move directly to a specific section

This question may be common, but despite my research efforts, I have been unable to find a solution. I want to issue a disclaimer that I am new to javascript and jQuery. Here is an overview of what I am trying to achieve: I want two images that, when cli ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...