Skip to content

Commit 8967fd7

Browse files
committed
fix($anchorScroll): make sure scrolling takes place when readyState === 'complete'
When navigating to a page with a hash in the URL, Firefox and IE do their native scrolling AFTER $anchorScroll, which cancels the applied `yOffset`. Waiting for `document.readyState` to be 'complete' solves the problem in Firefox. (In IE, the issue still appears when navigating to a URL (with a hash), but not when reloading the same URL.) Note, that with or without this fix subsequent calls to `$anchorScroll()` or changes to `$location.hash()` work as expected in all supported browsers.
1 parent 2614d4f commit 8967fd7

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/ng/anchorScroll.js

+16-1
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,7 @@ function $AnchorScrollProvider() {
168168
*/
169169
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
170170
var document = $window.document;
171+
var scrollScheduled = false;
171172

172173
// Helper function to get first anchor from a NodeList
173174
// (using `Array#some()` instead of `angular#forEach()` since it's more performant
@@ -234,6 +235,20 @@ function $AnchorScrollProvider() {
234235
}
235236
}
236237

238+
function scrollWhenReady() {
239+
if (document.readyState === 'complete') {
240+
$rootScope.$evalAsync(scroll);
241+
} else if (!scrollScheduled) {
242+
scrollScheduled = true;
243+
document.addEventListener('readystatechange', function unbindAndScroll() {
244+
if (document.readyState === 'complete') {
245+
document.removeEventListener('readystatechange', unbindAndScroll);
246+
$rootScope.$evalAsync(scroll);
247+
}
248+
});
249+
}
250+
}
251+
237252
function scroll() {
238253
var hash = $location.hash(), elm;
239254

@@ -255,7 +270,7 @@ function $AnchorScrollProvider() {
255270
if (autoScrollingEnabled) {
256271
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
257272
function autoScrollWatchAction() {
258-
$rootScope.$evalAsync(scroll);
273+
scrollWhenReady();
259274
});
260275
}
261276

0 commit comments

Comments
 (0)