How to scroll to top of the page in AngularJS?

JavascriptJqueryAngularjs

Javascript Problem Overview


I want to scroll to the top of the page after getting an ajax call response using angularjs. Basically, I am displaying alert messages on top of the page and I want to focus the alert message as the ajax response received.

Thanks

Javascript Solutions


Solution 1 - Javascript

You can use

$window.scrollTo(x, y);

where x is the pixel along the horizontal axis and y is the pixel along the vertical axis.

  1. Scroll to top

     $window.scrollTo(0, 0);
    
  2. Focus on element

     $window.scrollTo(0, angular.element('put here your element').offsetTop);   
    

Example

Update:

Also you can use $anchorScroll

Example

Solution 2 - Javascript

You can use $anchorScroll.

Just inject $anchorScroll as a dependency, and call $anchorScroll() whenever you want to scroll to top.

Solution 3 - Javascript

Ideally we should do it from either controller or directive as per applicable. Use $anchorScroll, $location as dependency injection.

Then call this two method as

$location.hash('scrollToDivID');
$anchorScroll();

Here scrollToDivID is the id where you want to scroll.

Assumed you want to navigate to a error message div as

<div id='scrollToDivID'>Your Error Message</div>

For more information please see this documentation

Solution 4 - Javascript

Don't forget you can also use pure JavaScript to deal with this situation, using:

window.scrollTo(x-coord, y-coord);

Solution 5 - Javascript

 $scope.$on('$stateChangeSuccess', function () {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
 });

Solution 6 - Javascript

use: $anchorScroll();

with $anchorScroll property

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFarjad HasanView Question on Stackoverflow
Solution 1 - JavascriptOleksandr T.View Answer on Stackoverflow
Solution 2 - JavascriptMuhammad RedaView Answer on Stackoverflow
Solution 3 - JavascriptPartha Sarathi GhoshView Answer on Stackoverflow
Solution 4 - JavascriptIgnacio AraView Answer on Stackoverflow
Solution 5 - JavascriptAlessandro GambaroView Answer on Stackoverflow
Solution 6 - JavascriptAther ParvezView Answer on Stackoverflow