74

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

0

6 Answers 6

156

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

Sign up to request clarification or add additional context in comments.

5 Comments

For focusing on element, $window.scrollTo(0, angular.element('put here your element').offset().top);
dont forget to inject $window in controller function definition. for example: function ($scope, $rootScope, $location, base_factory,$window)
@MuhammadReda when you say put here your element' is that the id of the element? for example I want to scroll to the top of an element with id of "directions_panel" so I entered that where you say 'put here your element' however I am getting an error. thanks for any help
@MuhammadReda I have it working now thanks. Instead of angular.element('put your element here').offsetTop I did document.getElementById('my_element').offsetTop. thanks for the help :)
I don't know why but these both codes are not working. I'm using it with ng-calendar directive. :(
31

You can use $anchorScroll.

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

1 Comment

Note that there's no animation (smooth scroll) available for $anchorScroll.
13

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

1 Comment

The above answer is for angularjs 1
4

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

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

Comments

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

Comments

-4

use: $anchorScroll();

with $anchorScroll property

1 Comment

The answer should be descriptive.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.