Animating ng-view on route change in AngularJS

Using timeouts and animation delays to make the view transitions look just right.

Mike Robinson
2 min readJun 23, 2014

I’m working on a website in AngularJS and am using ngAnimate for the ngView transitions. I was also making use of Dan Eden’s lovely Animate.css library of “Just-add-water CSS animations”. The effect I was shooting for would have the current view run the “fadeOutUp” animation, load the new content, and run the “fadeInDown” animation with the new content being presented from the top. Things were looking decent until the pages started to have enough content to require scrolling.

Check out this codepen to see what happens when you’re scrolled down the page and you click a link to change the page. The view stays scrolled to where the user was on the previous page. The ideal situation would be to have the view scroll back to the top when the new page is loaded.

Aha! The ngView has an “autoscroll” parameter that, when set to “true”, will scroll the view back to the top. You can see this in action at this codepen.

Unfortunately when using the “autoscroll” parameter, the view doesn’t scroll back to the top until the ng-enter animation has finished rendering, which also doesn’t look great.

The solution I’ve come up with is to use a timeout to scroll the view back to the top after the ng-leave animation is finished, and before the ng-enter animation starts. The ng-leave animation has a duration of 0.5 seconds (500 milliseconds). So in the $routeChangeSuccess event, I create a timeout that scrolls to the top after 500ms. The ng-enter animation has a 500 ms delay so it doesn’t start until the ng-leave animation has finished and the view has scrolled back to the top. Sweet!

Check out the final product in all its glory. The timeout function is at the bottom of the JavaScript.

--

--